Pandas Python - 格式化和返回週期物件的字串表示形式


要格式化和返回週期物件的字串表示形式,請使用 period.strftime() 方法。然後,將格式說明符設定為引數,如 strftime('%d-%b-%Y')。

首先,匯入所需的庫 −

import pandas as pd

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

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

顯示 Period 物件

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

顯示格式化的字串表示形式

print("\nString representation (format)...\n", period.strftime('%d-%b-%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 = 8, minute = 20, second = 45)

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

# display the result
print("\nString representation (format)...\n", period.strftime('%d-%b-%Y'))

# display the result
print("\nString representation (format with different directives)...\n",
period.strftime('%b. %d, %Y was a %A'))

輸出

這將產生以下程式碼

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

String representation (format)...
18-Sep-2021

String representation (format with different directives)...
Sep. 18, 2021 was a Saturday

更新於: 20-Oct-2021

959 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.