Python code to generate dates in a range

Today I needed to write a Python script where a part of it was to generate all dates in a range. I am sharing a simplified version of my code.

import datetime

def generate_dates(start_date, end_date):
td = datetime.timedelta(hours=24)
current_date = start_date
while current_date <= end_date:
print current_date
current_date += td

start_date = datetime.date(2010, 1, 25)
end_date = datetime.date(2010, 3, 5)
generate_dates(start_date, end_date)

As always, please share if you know other methods that serve the purpose.

Comments

Anonymous said…
import datetime

def generate_dates(start_date, end_date):
return (start_date + datetime.timedelta(days=d) for d in xrange(
(end_date - start_date).days + 1
))

start_date = datetime.date(2010, 1, 25)
end_date = datetime.date(2010, 3, 5)
for current_date in generate_dates(start_date, end_date):
print current_date
Bob Golobish said…
I am a beginning Python programmer. I am working my way through the tutorial "Think Like a Computer Scientist." I am having fun.

I tried your program and it works fine.

Here is why I'm contacting you. I want to schedule a series of tweets using HootSuite Pro. To do so, I need to generate a series of dates in the following format:

dd/mm/yyyy hh:mm

Start date:
01/01/2011 06:00

End date:
31/01/2011 06:00

I need to be able to change the start date and end date.

I have been doing this by hand, but I thought I should try to write a little program in Python.

Do you have any suggestions on where to start? I would appreciate it if you would point me in the right direction.

Peace.

Bob G.
Tamim Shahriar said…
@Bob, this link should be helpful: http://docs.python.org/library/datetime.html
Bob Golobish said…
Thanks. I looking at it now. Going to take some thought! : )
plagiats said…
Bob :
import time
time.strftime("%d/%m/%Y %H:%M")
time.strftime("%d/%m/%Y %H:%M", (2010, 12, 31, 13, 23, 11, 00, 00, 00))

=> '31/12/2010 13:23'
Unknown said…
Now how would you store each date in a list?

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code