-2

So I’m trying to piggyback off Sandeep’s answer to create a range of dates in Python: datetime - Creating a range of dates in Python - and using a list comprehension to get a list of datetime.dates between two given datetime.dates. Currently, it goes day by calendar day. What I am trying to do is modify this to go A) two days at a time (skip a day) and B) three days at a time (skip two days). I believe it should be a modification to the range - I just can't get it right!

Import datetime
Start_date=datetime.date(2020,1,1)
End_date=datetime.date.today()-datetime.timedelta(days=1)
dd = [start_date + datetime.timedelta(days=x) for x in range((end_date-start_date).days + 1)]
print(dd)

proposed:

dd = [start_date + datetime.timedelta(days=x) for x in range((end_date-start_date).days + 1,datetime.timedelta(days=3))]

Which does not work, giving a TypeError: 'datetime.timedelta' object cannot be interpreted as an integer error. Anyone can help?

drsxr
  • 29
  • 7

2 Answers2

0

The error as pointe out by juanpa.arrivllgaga user:5014455 is that in the list comprehension you are working with integers and not a datetime.date object, so keep things as integers.

Solution skipping N day between dates in the list:

N=3
dd = [start_date + datetime.timedelta(days=x) for x in range(0,(end_date-start_date).days + 1,N)]
dd
drsxr
  • 29
  • 7
0

You can use date.toordinal() and date.fromordinal():

from datetime import date, timedelta

start_date = date.today()
end_date = start_date + timedelta(days=15)
skip = 3

dd = [date.fromordinal(d) for d in range(start_date.toordinal(), end_date.toordinal(), skip)]
RootTwo
  • 4,288
  • 1
  • 11
  • 15