Python Pandas - 將給定的 Timestamp 轉換為具有每月頻率的週期


要將給定的 Timestamp 轉換為 Period,請使用 timestamp.to_period() 方法。在其中,使用 freq 引數設定頻率。對於每月頻率,將 freq 設定為 M。

首先,匯入所需的庫 −

import pandas as pd

在 Pandas 中設定 Timestamp 物件

timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

將 Timestamp 轉換為 Period。我們使用值“M”的“freq”引數將頻率設定為每月

timestamp.to_period(freq='M')

示例

以下為程式碼

import pandas as pd

# set the timestamp object in Pandas
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

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

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

輸出

將生成以下程式碼

Timestamp...
 2021-09-18 11:50:20.000033
Timestamp to Period with monthly frequency...
 2021-09

更新於:2021-10-13

448 次檢視

開啟您的事業

透過完成課程取得認證

開始
廣告
© . All rights reserved.