3

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.

Nick Stinemates
  • 41,511
  • 21
  • 59
  • 60

2 Answers2

2
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
  • 842,883
  • 184
  • 1,785
  • 1,677
0
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 O.
  • 15,659
  • 11
  • 54
  • 84