Python Pandas - 格式化期間物件並以 24 小時格式顯示時間


若要格式化期間物件,請使用 **period.strftime()** 方法,若要以 24 小時格式顯示時間,請將引數設定為 %H.

首先,匯入必需的庫 −

import pandas as pd

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

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

顯示期間物件

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

顯示結果。此處,時間以 24 小時格式顯示,即 [00,23]

print("\nString representation (24-Hour format)...\n", period.strftime('%H'))

範例

以下是程式碼

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)

# display the result
# Here, Time is displayed with 24-Hour format i.e. [00,23]
print("\nString representation (24-Hour format)...\n", period.strftime('%H'))

輸出

這將產生以下程式碼

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

String representation (24-Hour format)...
17

更新於:20-Oct-2021

854 檢視

開啟您的職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.