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


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

首先,匯入所需的庫 −

import pandas as pd

在 Pandas 中建立 timestamp 物件

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

將 timestamp 轉換為 Period。我們使用值 'W' 設定了 "freq" 引數作為每週頻率

timestamp.to_period(freq='W')

例子

以下為程式碼

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 weekly using the "freq" parameter with value 'W'
print("\nTimestamp to Period with weekly frequency...\n", timestamp.to_period(freq='W'))

輸出

將生成以下程式碼

Timestamp...
 2021-09-18 11:50:20.000033
Timestamp to Period with weekly frequency...
 2021-09-13/2021-09-19

更新於: 13-Oct-2021

310 次瀏覽

開啟屬於你的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.