Generate list of datetimes with hourly timedelta

拟墨画扇 提交于 2020-03-24 03:56:08

问题


I am using this code to generate a range of hourly datetime's:

from datetime import datetime, timedelta

def daterange(start_date, end_date):
    # timedelta only has days and seconds attributes
    for n in range(int ((end_date - start_date).seconds/3600 + 1)):
        yield start_date + timedelta(n)

start_date = datetime(2013, 1, 1, 14, 00)
end_date = datetime(2015, 6, 2, 5, 00)
for single_date in daterange(start_date, end_date):
    print single_date.strftime("%Y-%m-%d %H:%M")

But I am getting an unexpected result:

2013-01-01 14:00
2013-01-02 14:00
2013-01-03 14:00
2013-01-04 14:00
2013-01-05 14:00
2013-01-06 14:00
2013-01-07 14:00
2013-01-08 14:00
2013-01-09 14:00
2013-01-10 14:00
2013-01-11 14:00
2013-01-12 14:00
2013-01-13 14:00
2013-01-14 14:00
2013-01-15 14:00
2013-01-16 14:00

How can I better specify an hourly interval with the timedelta seconds attribute? I'd rather not use external packages like NumPy.


回答1:


You can build the timedelta directly and then add like:

Code:

def daterange(start_date, end_date):
    delta = timedelta(hours=1)
    while start_date < end_date:
        yield start_date
        start_date += delta

Test Code:

from datetime import datetime, timedelta

start_date = datetime(2013, 1, 1, 14, 00)
end_date = datetime(2015, 6, 2, 5, 00)
for single_date in daterange(start_date, end_date):
    print(single_date.strftime("%Y-%m-%d %H:%M"))

Results:

2013-01-01 14:00
2013-01-01 15:00
2013-01-01 16:00
2013-01-01 17:00
2013-01-01 18:00
2013-01-01 19:00
2013-01-01 20:00
2013-01-01 21:00
2013-01-01 22:00
2013-01-01 23:00
2013-01-02 00:00
2013-01-02 01:00


来源:https://stackoverflow.com/questions/48655358/generate-list-of-datetimes-with-hourly-timedelta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!