The Python Oracle

Print all day-dates between two dates

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2

--

Chapters
00:00 Print All Day-Dates Between Two Dates
00:20 Accepted Answer Score 501
00:50 Answer 2 Score 4
00:59 Answer 3 Score 8
01:07 Answer 4 Score 60
01:23 Thank you

--

Full question
https://stackoverflow.com/questions/7274...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #datetime

#avk47



ACCEPTED ANSWER

Score 501


I came up with this:

from datetime import date, timedelta

start_date = date(2008, 8, 15) 
end_date = date(2008, 9, 15)    # perhaps date.today()

delta = end_date - start_date   # returns timedelta

for i in range(delta.days + 1):
    day = start_date + 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. Otherwise:

# To remove the end date, delete the "+ 1" 
# at the end of the range function:
for i in range(delta.days):

# To remove the start date, insert a 1 
# to the beginning of the range function:
for i in range(1, delta.days + 1):



ANSWER 2

Score 60


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)



ANSWER 3

Score 8


import datetime

d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
    print (d1 + datetime.timedelta(i)).isoformat()



ANSWER 4

Score 4


import datetime

begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)

next_day = begin
while True:
    if next_day > end:
        break
    print next_day
    next_day += datetime.timedelta(days=1)