Python Pandas - 將給定的時間戳轉換為週期


要將給定的時間戳轉換為週期,請使用 timestamp.to_period() 函式。在內部,使用 freq 引數設定頻率。

首先,匯入必需的計算機庫 −

import pandas as pd

在 Pandas 中設定時間戳物件

timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

現在,將時間戳轉換為週期。我們已經使用值“M”將頻率設定為月份,即“freq”引數

timestamp.to_period(freq='M')

示例

以下為程式碼

import pandas as pd

# set the timestamp object in Pandas
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

# display the Timestamp
print("Timestamp...\n", timestamp)

# convert timestamp to Period
# we have set the frequency as Month using the "freq" parameter with value 'M'
print("\nTimestamp to Period...\n", timestamp.to_period(freq='M'))

輸出

這將生成以下程式碼

Timestamp...
 2021-09-14 15:12:34.261811624

Timestamp to Period...
2021-09

更新時間:2021-10-13

741 次檢視

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告