views:

55

answers:

2

I have 2 dates and I am trying to build labels of an x-axis of a plot.

As such, I need a way to take 2 datetime objects, i.e 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so:

["2009-10-12", "2009-10-13", "2009-10-14", ..., "2009-10-19", "2009-10-20"]

What libraries should I use to assist? I have a feeling the datetime module and the timedelta functionality will help quite a bit.

I can include code if it makes sense to, but I have a feeling there's something built in to the python libraries that allow for this to be real easy. I seem to just be missing it.

+3  A: 
import datetime

first=datetime.date(2009,10,12)
last=datetime.date(2009,10,20)
adate=first
dates=[]
while adate<=last:
    dates.append(adate)
    adate+=datetime.timedelta(1)
print(dates)

Or, for lovers of list comprehension:

len=(last-first).days
dates=[first+datetime.timedelta(n) for n in range(len+1)]
unutbu
Thanks: I really love comprehensions :)
Attila Oláh
A: 
from datetime import date, timedelta

a, b = date(1010, 10, 12), date(1010, 10, 20)
times = [a + timedelta(x) for x in xrange((b-a).days)]

# If you want to format them:
times = [x.strftime('%Y-%m-%d') for x in times]
Attila Oláh
This is with datetime.date objects, but datetime.datetime should work the same.
Attila Oláh