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.
As always, please share if you know other methods that serve the purpose.
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
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
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.
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'