Print all day-dates between two dates

200

For example:

from datetime import date

d1 = date(2008,8,15)
d2 = date(2008,9,15)

I'm looking for simple code to print all dates in-between:

2008,8,15  
2008,8,16  
2008,8,17  
...  
2008,9,14  
2008,9,15

Thanks

This question is tagged with python datetime

~ Asked on 2011-09-01 17:44:08

The Best Answer is


381

I came up with this:

from datetime import date, timedelta

sdate = date(2008, 8, 15)   # start date
edate = date(2008, 9, 15)   # end date

delta = edate - sdate       # as timedelta

for i in range(delta.days + 1):
    day = sdate + timedelta(days=i)
    print(day)

The output:

2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15

Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.

~ Answered on 2011-09-01 17:48:12


48

Using a list comprehension:

from datetime import date, timedelta

d1 = date(2008,8,15)
d2 = date(2008,9,15)

# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]

for d in dd:
    print d

# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)

~ Answered on 2013-04-12 14:21:49


Most Viewed Questions: