Python Pandas——使用特定的時間序列頻率從 DateTimeIndex 中提取秒


要從特定時間序列頻率的 DateTimeIndex 中提取秒,請使用 DateTimeIndex.second 屬性。

首先,匯入所需的庫 −

import pandas as pd

用週期為 6、頻率為 S(即秒)建立 DatetimeIndex。時區為澳大利亞/悉尼 −

datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='S')

顯示 DateTimeIndex −

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

獲取秒 −

print("\nGetting the seconds..\n",datetimeindex.second)

示例

以下是程式碼 −

import pandas as pd

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

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

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

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

輸出

這將生成以下程式碼 −

DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-20 02:30:51+11:00',
'2021-10-20 02:30:52+11:00', '2021-10-20 02:30:53+11:00',
'2021-10-20 02:30:54+11:00', '2021-10-20 02:30:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='S')
DateTimeIndex frequency...
<Second>

Getting the seconds..
Int64Index([50, 51, 52, 53, 54, 55], dtype='int64')

更新於:18-Oct-2021

440 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.