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.