Python Pandas - 使用特定时间序列频率从 DateTimeIndex 提取小时


要使用特定时间序列频率从 DateTimeIndex 提取小时,请使用 **DateTimeIndex.hour** 属性。

首先,导入所需的库 −

import pandas as pd

DatetimeIndex 的周期为 6,频率为 H,即小时。时区为澳大利亚/悉尼 −

datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')

显示 DateTimeIndex −

print("DateTimeIndex...\n", datetimeindex)

获取小时 −

print("\nGetting the hour..\n",datetimeindex.hour)

示例

以下是代码 −

import pandas as pd

# DatetimeIndex with period 6 and frequency as H i.e. hour
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# get the hour
print("\nGetting the hour..\n",datetimeindex.hour)

输出

这将生成以下代码 −

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-20 03:35:55+11:00',
'2021-10-20 04:35:55+11:00', '2021-10-20 05:35:55+11:00',
'2021-10-20 06:35:55+11:00', '2021-10-20 07:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='H')

DateTimeIndex frequency...
<Hour>

Getting the hour..
Int64Index([2, 3, 4, 5, 6, 7], dtype='int64')

更新于: 2021 年 10 月 18 日

4K+ 浏览量

开创您的职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.