2

可能重复:
在 Python 中遍历一系列日期

我有一个方法可以传入开始日期和结束日期。最终结果是我想要开始日期和结束日期之间的所有日期作为列表。例如,如果开始日期是 '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])
4

3 回答 3

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']
于 2013-01-14T23:17:14.313 回答
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)]
于 2013-01-14T23:14:49.517 回答
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']
于 2013-01-14T23:29:11.677 回答