在python中迭代日期

Iterating over date in python

本问题已经有最佳答案,请猛点这里访问。

这是我的代码:

1
2
3
4
5
6
7
8
MYDATE = []
start_date ="2011-01-01"
stop_date ="2013-05-01"

start = start_date.strftime("%Y-%m-%d")
stop = stop_date.strftime("%Y-%m-%d")
for r in .......:
    MYDATE.append((r,r))

我如何迭代start_datestop_date之间的日期?


好的在线信息技术depends你希望到迭代。村里的日子吗?月村吗?使用timedelta会解决你的问题。 </P >

1
2
3
4
5
6
7
8
9
10
11
from datetime import datetime

start_date ="2011-01-01"
stop_date ="2013-05-01"

start = datetime.strptime(start_date,"%Y-%m-%d")
stop = datetime.strptime(stop_date,"%Y-%m-%d")

from datetime import timedelta
while start < stop:
    start = start + timedelta(days=1)  # increase day one by one

另一个方法对itearete通用relativedelta月冰 </P >

1
2
from dateutil.relativedelta import relativedelta
start = start + relativedelta(months = +1)


timedelta怎么样? </P >

1
2
3
4
5
6
7
8
start = datetime.now()
end = start + timedelta(days=10)

tmp = start

while tmp < end:
    print tmp
    tmp = tmp + timedelta(days=1) # replace the interval at will

印 </P >

1
2
3
4
5
6
7
8
9
10
2014-04-07 10:42:14.943790
2014-04-08 10:42:14.943790
2014-04-09 10:42:14.943790
2014-04-10 10:42:14.943790
2014-04-11 10:42:14.943790
2014-04-12 10:42:14.943790
2014-04-13 10:42:14.943790
2014-04-14 10:42:14.943790
2014-04-15 10:42:14.943790
2014-04-16 10:42:14.943790