我正在使用此代码生成一小时datetime
的范围:
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")
但是我得到了意想不到的结果:
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
如何使用timedelta
秒属性更好地指定每小时间隔?我宁愿不使用像NumPy这样的外部软件包。
答案 0 :(得分:4)
您可以直接构建timedelta
,然后添加如下:
def daterange(start_date, end_date):
delta = timedelta(hours=1)
while start_date < end_date:
yield start_date
start_date += delta
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"))
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