[英]Enumerate a DateRange
I have 2 dates and I am trying to build labels of an x-axis of a plot. 我有两个日期,我正在尝试建立一个情节的x轴标签。
As such, I need a way to take 2 datetime objects, ie 2009-10-12 00:00:00 and 2009-10-20 00:00:00 and generate a list like so: 因此,我需要一种方法来获取2个日期时间对象,即2009-10-12 00:00:00和2009-10-20 00:00:00并生成如下列表:
["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.
我有一种感觉, datetime模块和timedelta功能将有所帮助。
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. 我可以包含代码,如果它有意义,但我有一种感觉,python库中内置了一些内容,可以让它变得非常容易。 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.