我想生成连续的日期

时间:2012-11-24 08:54:32

标签: python date datetime

我有这样的代码:

import time
from datetime import date
startyear = raw_input("start year: ")
startmonth = raw_input("start month: ")
startday = raw_input("start day: ")
endyear = raw_input("end year: ")
endmonth = raw_input("end month: ")
endday = raw_input("end day: ")

startdate = date(int(startyear), int(startmonth), int(startday))
while startdate < date(int(endyear), int(endmonth), int(endday)):
    print startdate
    startdate = startdate.replace(day=startdate.day + 1)

这段代码的作用是:
1.手动输入确认开始和结束日期
2.生成他们之间的日期列表

但问题是,如果我设置日期,例如,
startdate: 2012-10-28
enddate: 2012-11-4
输出就像:

2012-10-28
2012-10-29
2012-10-30
2012-10-31
ValueError: day is out of range for month

我希望输出如下:

2012-10-28
2012-10-29
2012-10-30
2012-10-31
2012-11-01
2012-11-02
2012-11-03
2012-11-04

所以我希望这些日期能够持续一个月。 有什么建议?任何帮助都会非常棒。

2 个答案:

答案 0 :(得分:7)

有一个名为python-dateutil的模块,对于这类事情非常有用:

from datetime import datetime
from dateutil.rrule import rrule, DAILY

list(rrule(DAILY, dtstart=datetime(2012, 11, 24), until=datetime(2012,11,30)))
# [datetime.datetime(2012, 11, 24, 0, 0), datetime.datetime(2012, 11, 25, 0, 0), datetime.datetime(2012, 11, 26, 0, 0), datetime.datetime(2012, 11, 27, 0, 0), datetime.datetime(2012, 11, 28, 0, 0), datetime.datetime(2012, 11, 29, 0, 0), datetime.datetime(2012, 11, 30, 0, 0)]

并且还有其他选项,例如,一周中的几天(对于工作周内仅包括MO,TU,WE,TH,FR非常有用):

from dateutil.rrule import MO, WE
list(rrule(DAILY, byweekday=[MO, WE], dtstart=datetime(2012, 11, 24), until=datetime(2012,11,30))
# [datetime.datetime(2012, 11, 26, 0, 0), datetime.datetime(2012, 11, 28, 0, 0)]

答案 1 :(得分:5)

而不是startdate.replace(),您应该使用timedelta ...

from datetime import date, timedelta
# Get input here...
while startdate < date(int(endyear), int(endmonth), int(endday)):
    print startdate
    startdate += timedelta(days=1)