创建自定义日期范围,每天22小时python
作者:互联网
我正在和熊猫一起工作,想要创建一个长达一个月的自定义日期范围,周日从周日晚上6点开始,到周五下午4点结束.每天有22个小时,所以例如周日下午6点到周一下午4点,周一下午6点到周二下午4点等.
我试过day_range = pd.date_range(datetime(2016,9,12,18),datetime.now(),freq =’H’)但是这总是在24小时内给我.
有什么建议?
解决方法:
date_range
需要Custom Business Hour
:
cbh = pd.offsets.CustomBusinessHour(start='06:00',
end='16:00',
weekmask='Mon Tue Wed Thu Fri Sat')
print (cbh)
<CustomBusinessHour: CBH=06:00-16:00>
day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh)
print (day_range)
DatetimeIndex(['2016-09-13 06:00:00', '2016-09-13 07:00:00',
'2016-09-13 08:00:00', '2016-09-13 09:00:00',
'2016-09-13 10:00:00', '2016-09-13 11:00:00',
'2016-09-13 12:00:00', '2016-09-13 13:00:00',
'2016-09-13 14:00:00', '2016-09-13 15:00:00',
...
'2016-10-11 08:00:00', '2016-10-11 09:00:00',
'2016-10-11 10:00:00', '2016-10-11 11:00:00',
'2016-10-11 12:00:00', '2016-10-11 13:00:00',
'2016-10-11 14:00:00', '2016-10-11 15:00:00',
'2016-10-12 06:00:00', '2016-10-12 07:00:00'],
dtype='datetime64[ns]', length=252, freq='CBH')
测试 – 它省略了星期天:
day_range = pd.date_range(pd.datetime(2016,9,12,18),pd.datetime.now(),freq=cbh)[45:]
print (day_range)
DatetimeIndex(['2016-09-17 11:00:00', '2016-09-17 12:00:00',
'2016-09-17 13:00:00', '2016-09-17 14:00:00',
'2016-09-17 15:00:00', '2016-09-19 06:00:00',
'2016-09-19 07:00:00', '2016-09-19 08:00:00',
'2016-09-19 09:00:00', '2016-09-19 10:00:00',
...
'2016-10-11 08:00:00', '2016-10-11 09:00:00',
'2016-10-11 10:00:00', '2016-10-11 11:00:00',
'2016-10-11 12:00:00', '2016-10-11 13:00:00',
'2016-10-11 14:00:00', '2016-10-11 15:00:00',
'2016-10-12 06:00:00', '2016-10-12 07:00:00'],
dtype='datetime64[ns]', length=207, freq='CBH')
标签:python,datetime,pandas,date-range,hour 来源: https://codeday.me/bug/20190702/1352490.html