Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Format the Period object and display the Time with 24-Hour format
To format the Period object and display time in 24-hour format, use the period.strftime() method with the %H parameter. The %H format code represents hours in 24-hour format (00-23).
Creating a Period Object
First, let's create a Pandas Period object with a specific date and time ?
import pandas as pd
# Create a Period object with second frequency
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
print("Period object:")
print(period)
Period object: 2021-09-18 17:20:45
Formatting with 24-Hour Time
Use strftime() with %H to extract the hour in 24-hour format ?
import pandas as pd
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
# Format hour in 24-hour format
hour_24 = period.strftime('%H')
print("24-hour format:", hour_24)
# Compare with 12-hour format
hour_12 = period.strftime('%I %p')
print("12-hour format:", hour_12)
24-hour format: 17 12-hour format: 05 PM
Common Time Format Codes
Here are useful format codes for time formatting ?
import pandas as pd
period = pd.Period(freq="S", year=2021, month=9, day=18, hour=17, minute=20, second=45)
print("Hour (24-hour):", period.strftime('%H'))
print("Hour (12-hour):", period.strftime('%I'))
print("Minute:", period.strftime('%M'))
print("Second:", period.strftime('%S'))
print("Full time (24h):", period.strftime('%H:%M:%S'))
print("AM/PM:", period.strftime('%p'))
Hour (24-hour): 17 Hour (12-hour): 05 Minute: 20 Second: 45 Full time (24h): 17:20:45 AM/PM: PM
Format Codes Summary
| Format Code | Description | Example |
|---|---|---|
%H |
Hour (24-hour format) | 00-23 |
%I |
Hour (12-hour format) | 01-12 |
%M |
Minute | 00-59 |
%S |
Second | 00-59 |
%p |
AM/PM | AM, PM |
Conclusion
Use strftime('%H') to format Pandas Period objects and display hours in 24-hour format. This method provides flexible time formatting with various format codes for different time components.
Advertisements
