我想创建一个带小时增量的日期列表,如下所示:
['2012060100', '2012060101', '2012060102', '2012060103', '2012060104', '2012060105', '2012060106', '2012060107', '2012060108', '2012060109', '2012060110', '2012060111', '2012060112', '2012060113', '2012060114', '2012060115', '2012060116', '2012060117', '2012060118', '2012060119', '2012060120', '2012060121', '2012060122', '2012060123', '2012060200', '2012060201', '2012060202'... '2012083122', '2012083123']
我正在尝试这样的事情:
deb = '20120601'
fin = '20120831'
start = datetime.datetime.strptime(deb, "%Y%m%d")
end = datetime.datetime.strptime(fin, "%Y%m%d")
date_lst = [start + datetime.timedelta(days=x) for x in range(0, ((end-start).days)+1)]
date_list = [dt.strftime("%Y%m%d") for dt in date_lst]
但它只打印start
和end
之间的日期列表,如下所示:
['20120601', '20120602', '20120603', '20120604', ... , '20120830', '20120831']
答案 0 :(得分:4)
如果您需要数小时,则需要在格式字符串中包含'%H'
。如果添加以天为单位的timedelta
,您也不会花费数小时。
from datetime import datetime as dt, timedelta
deb = '20120601'
fin = '20120831'
start = dt.strptime(deb, "%Y%m%d")
end = dt.strptime(fin, "%Y%m%d") + timedelta(days=1)
def hour_range(start, end):
while start < end:
yield start
start += timedelta(hours=1)
date_list = [h.strftime('%Y%m%d%H') for h in hour_range(start, end)]
答案 1 :(得分:2)
您只需按天而不是小时增加。试试这个。
deb = '20120601'
fin = '20120831'
start = datetime.datetime.strptime(deb, "%Y%m%d")
end = datetime.datetime.strptime(fin, "%Y%m%d")
dif = int((end-start).total_seconds()/3600) ## time difference in hours
date_list = [(start + datetime.timedelta(hours=x)).strftime("%Y%m%d%H") for x in range(dif+1)]
答案 2 :(得分:1)
你不会按小时增加:
date_lst = [start + datetime.timedelta(hours=x) for x in range(0, 24*((end-start).days)+1)]
date_list = [dt.strftime("%Y%m%d%H") for dt in date_lst]