我有一个方法可以传递开始日期和结束日期。最终结果是我希望开始日期和结束日期之间的所有日期都作为列表。例如,如果开始日期是“2013-01-01”,结束日期是“2013-01-04”那么['2013-01-01','2013-01-02','2013-01-03 ','2013-01-04']应该退回。我可以做类似下面的事情。但是想知道是否有一种我没有考虑的简单方法
year = int(startdate.split('-')[0])
month = int(startdate.split('-')[1])
day = int(startdate.split('-')[2])
答案 0 :(得分:2)
>>> from datetime import datetime, timedelta
>>> starttime = datetime.strptime('2013-01-01', '%Y-%m-%d')
>>> endtime = datetime.strptime('2013-01-04', '%Y-%m-%d')
>>> [starttime + timedelta(days=i) for i in range((endtime - starttime).days + 1)]
[datetime.datetime(2013, 1, 1, 0, 0), datetime.datetime(2013, 1, 2, 0, 0), datetime.datetime(2013, 1, 3, 0, 0), datetime.datetime(2013, 1, 4, 0, 0)]
>>> list(map(lambda x: x.strftime('%Y-%m-%d'), _))
['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04']
答案 1 :(得分:1)
这应该有效:
from datetime import datetime
from datetime import timedelta
d1 = datetime.strptime('2013-01-01', '%Y-%m-%d')
d2 = datetime.strptime('2013-01-04', '%Y-%m-%d')
[d1 + timedelta(days=x) for x in range(0, (d2 - d1).days + 1)]
答案 2 :(得分:0)
我会去:
from dateutil import parser as dateparser
from dateutil.rrule import rrule, DAILY
sd = dateparser.parse('2013-01-01')
ed = dateparser.parse('2013-01-04')
dates = (rrule(DAILY, sd, until=ed))
fmt = '{:%Y-%m-%d}'
print map(fmt.format, dates)
# ['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04']