I'm trying to print odd dates between two days but I'm getting all dates between the range. How can I only print the odd dates using python. For example: 15-8-2008, 17-8-2008, 19-8-2008, 21-8-2008, 23-8-2008
from datetime import date, timedelta
start = date(2008, 8, 15)
end = date(2008, 9, 15)
delta = end - start
for i in range(delta.days 1):
day = start timedelta(days=i)
print(day)
CodePudding user response:
Try this
from datetime import date, timedelta
start = date(2008, 8, 15)
end = date(2008, 9, 15)
delta = end - start
for i in range(delta.days 1):
day = start timedelta(days=i)
if int(str(day)[-2:]) %2!= 0:
print(day)
will give
2008-08-15
2008-08-17
2008-08-19
2008-08-21
2008-08-23
2008-08-25
2008-08-27
2008-08-29
2008-08-31
2008-09-01
2008-09-03
2008-09-05
2008-09-07
2008-09-09
2008-09-11
2008-09-13
2008-09-15
CodePudding user response:
If you want to print only odd number of days then this code might help you. Please check this code. This code will give only odd days.
from datetime import date, timedelta
start = date(2008, 8, 15)
end = date(2008, 9, 15)
delta = end - start
for i in range(delta.days 1):
day = start timedelta(days=i)
if int(str(day).split("-")[2]) % 2 != 0:
print(day)
Here is the output of following code.
2008-08-15
2008-08-17
2008-08-19
2008-08-21
2008-08-23
2008-08-25
2008-08-27
2008-08-29
2008-08-31
2008-09-01
2008-09-03
2008-09-05
2008-09-07
2008-09-09
2008-09-11
2008-09-13
2008-09-15