我有一个 begin_datedatetime.date(2012, 9, 1)
和一个 end_datedatetime.date(2012, 9, 30)
我想要一个迭代器或包含日期 2012/9/1 到 2012/9/30 的列表。除了循环之外还有什么方法可以制作迭代器或列表
使用生成器:
from datetime import date, timedelta
def dategenerator(start, end):
current = start
while current <= end:
yield current
current += timedelta(days=1)
演示:
>>> for dt in dategenerator(date(2012, 9, 1), date(2012, 9, 30)):
... print dt
...
2012-09-01
2012-09-02
2012-09-03
2012-09-04
2012-09-05
2012-09-06
2012-09-07
2012-09-08
2012-09-09
2012-09-10
2012-09-11
2012-09-12
2012-09-13
2012-09-14
2012-09-15
2012-09-16
2012-09-17
2012-09-18
2012-09-19
2012-09-20
2012-09-21
2012-09-22
2012-09-23
2012-09-24
2012-09-25
2012-09-26
2012-09-27
2012-09-28
2012-09-29
2012-09-30
如果没有隐式循环,您可以执行以下操作:
from datetime import date
from dateutil.rrule import rrule, DAILY
iterdates=iter(rrule(DAILY, dtstart=date(2012, 9, 1), until=date(2012, 9, 30)))