在python中迭代日期

时间:2014-04-07 08:20:43

标签: python

这是我的代码:

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之间迭代日期?

2 个答案:

答案 0 :(得分:9)

这取决于您希望如何迭代。几天?几个月?使用timedelta可以解决您的问题。

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

迭代几个月的另一种方法是使用relativedelta

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

答案 1 :(得分:0)

timedelta怎么办?

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

打印

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