我想创建一个日期列表,总结前三个小时,然后是接下来的三个小时。就像是:
['2016/05/01-00-02h', '2016/05/01-03-05h', '2016/05/01-06-08h',.....'2016/05/31-21-23h']
。到目前为止,我只有一个没有摘要的日期列表。
from datetime import datetime as dt, timedelta
deb = '20160501'
fin = '20160531'
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)]
答案 0 :(得分:0)
我认为您可以使用pandas
:
import pandas as pd
dates = pd.date_range('2016-05-01', '2016-06-01', freq='2h')
result = pd.IntervalIndex.from_breaks(dates, closed='left').tolist()
#[Interval('2016-05-01', '2016-05-01 02:00:00', closed='left'),
#Interval('2016-05-01 02:00:00', '2016-05-01 04:00:00', closed='left'),
#Interval('2016-05-01 04:00:00', '2016-05-01 06:00:00', closed='left')
#...
#'2016-05-31 20:00:00', closed='left'),
#Interval('2016-05-31 20:00:00', '2016-05-31 22:00:00', closed='left'),
#Interval('2016-05-31 22:00:00', '2016-06-01', closed='left')]
答案 1 :(得分:0)
将其视为算术。将开始时间设置为凌晨2点,然后将其增加timedelta(hours=3)
,直到您生成所有需要的时间点。 (给定间隔,在你翻到第二天之前有8个时间点。)例如:
start += timedelta(hours=2) # Advance to 2am
while start < end:
yield start
start += timedelta(hours=3)