开发者

Enumerate a DateRange

开发者 https://www.devze.com 2022-12-18 06:09 出处:网络
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 200开发者_如何学C9-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a

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 200开发者_如何学C9-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.


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)]


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消