我正在尝试在Python中指定日期范围,该日期范围从当天前一天开始。但是,我希望该日期范围从10:00:00开始。
这是我目前使用的代码
import pandas as pd
import datetime as dt
date = dt.datetime.today() - dt.timedelta(days=1)
date_range = pd.date_range(date, freq='60min', periods=24)
但是,这从00:00:00开始。我已经尝试了几种方法来修改上面的代码,让它在10:00:00开始,但没有工作。有人可以帮忙吗?
澄清一下:我正在使用Pandas,因为这个日期范围将用作数据帧的索引。
答案 0 :(得分:3)
您可以构建另一个日期时间,但只使用日,月,年组件和偏移量:
In [87]:
date = dt.datetime.today() - dt.timedelta(days=1)
date = dt.datetime(date.year, date.month, date.day) + dt.timedelta(hours=10)
date_range = pd.date_range(date, freq='60min', periods=24)
date_range
Out[87]:
DatetimeIndex(['2016-11-22 10:00:00', '2016-11-22 11:00:00',
'2016-11-22 12:00:00', '2016-11-22 13:00:00',
'2016-11-22 14:00:00', '2016-11-22 15:00:00',
'2016-11-22 16:00:00', '2016-11-22 17:00:00',
'2016-11-22 18:00:00', '2016-11-22 19:00:00',
'2016-11-22 20:00:00', '2016-11-22 21:00:00',
'2016-11-22 22:00:00', '2016-11-22 23:00:00',
'2016-11-23 00:00:00', '2016-11-23 01:00:00',
'2016-11-23 02:00:00', '2016-11-23 03:00:00',
'2016-11-23 04:00:00', '2016-11-23 05:00:00',
'2016-11-23 06:00:00', '2016-11-23 07:00:00',
'2016-11-23 08:00:00', '2016-11-23 09:00:00'],
dtype='datetime64[ns]', freq='60T')
答案 1 :(得分:2)
试
today = pd.datetime.today().date()
today - pd.offsets.Hour(14)
Timestamp('2016-11-22 10:00:00')
然后使用pd.date_range
pd.date_range(today - pd.offsets.Hour(14), periods=24, freq='H')
DatetimeIndex(['2016-11-22 10:00:00', '2016-11-22 11:00:00',
'2016-11-22 12:00:00', '2016-11-22 13:00:00',
'2016-11-22 14:00:00', '2016-11-22 15:00:00',
'2016-11-22 16:00:00', '2016-11-22 17:00:00',
'2016-11-22 18:00:00', '2016-11-22 19:00:00',
'2016-11-22 20:00:00', '2016-11-22 21:00:00',
'2016-11-22 22:00:00', '2016-11-22 23:00:00',
'2016-11-23 00:00:00', '2016-11-23 01:00:00',
'2016-11-23 02:00:00', '2016-11-23 03:00:00',
'2016-11-23 04:00:00', '2016-11-23 05:00:00',
'2016-11-23 06:00:00', '2016-11-23 07:00:00',
'2016-11-23 08:00:00', '2016-11-23 09:00:00'],
dtype='datetime64[ns]', freq='H')
答案 2 :(得分:0)
创建一个字符串日期,然后将其解析为日期时间日期
from datetime import timedelta
from datetime import date
import datetime as datetime
previous_day=pd.datetime.today().date()-datetime.timedelta(days=1)
start_datetime=datetime.datetime.strptime(str(previous_day)+' 10:00:00','%Y-%m-%d %H:%M:%S')
date_range = pd.date_range(start_datetime, freq='60min', periods=24)
print(date_range)
输出:
DatetimeIndex(['2021-03-25 10:00:00', '2021-03-25 11:00:00',
'2021-03-25 12:00:00', '2021-03-25 13:00:00',
'2021-03-25 14:00:00', '2021-03-25 15:00:00',
'2021-03-25 16:00:00', '2021-03-25 17:00:00',
'2021-03-25 18:00:00', '2021-03-25 19:00:00',
'2021-03-25 20:00:00', '2021-03-25 21:00:00',
'2021-03-25 22:00:00', '2021-03-25 23:00:00',
'2021-03-26 00:00:00', '2021-03-26 01:00:00',
'2021-03-26 02:00:00', '2021-03-26 03:00:00',
'2021-03-26 04:00:00', '2021-03-26 05:00:00',
'2021-03-26 06:00:00', '2021-03-26 07:00:00',
'2021-03-26 08:00:00', '2021-03-26 09:00:00'],
dtype='datetime64[ns]', freq='60T')