Python Pandas - 以年頻率將 Period 物件返回為時間戳


要將 Period 物件以年頻率返回為時間戳,請使用 period.to_timestamp() 方法,並設定 freq 引數為 ‘Y’。

首先,匯入所需的庫 −

import pandas as pd

pandas.Period 表示一個時間段。建立一個 Period 物件

period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 17, minute = 20, second = 45)

顯示 Period 物件

print("Period...\n", period)

返回 Period 物件的時間戳表示形式。我們使用 "freq" 引數設定了頻率。頻率設定為 'Y',即每年

print("\nPeriod to Timestamp with yearly (year-end) frequency...\n", period.to_timestamp(freq='Y'))

示例

以下是程式碼

import pandas as pd

# The pandas.Period represents a period of time
# Creating a Period object
period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 17, minute = 20, second = 45)

# display the Period object
print("Period...\n", period)

# Return the Timestamp representation of the Period object
# We have set the frequency using the "freq" parameter
# The frequency is set as 'Y' i.e. yearly
print("\nPeriod to Timestamp with yearly (year-end) frequency...\n", period.to_timestamp(freq='Y'))

輸出

這將會生成以下程式碼

Period...
2021-09-18 17:20:45

Period to Timestamp with yearly (year-end) frequency...
2021-12-31 00:00:00

更新於: 20-Oct-2021

85 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告