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 - Get the hour of the day component of the Period
To get the hour of the day component of the Period, use the period.hour property. This property returns an integer value representing the hour component (0-23) of a Pandas Period object.
Creating Period Objects
First, let's import pandas and create Period objects with datetime information ?
import pandas as pd
# Creating Period objects with datetime strings
period1 = pd.Period("2020-09-23 05:55:30")
period2 = pd.Period(freq="H", year=2021, month=7, day=16, hour=2, minute=35)
print("Period1:", period1)
print("Period2:", period2)
Period1: 2020-09-23 05:55:30 Period2: 2021-07-16 02:00
Extracting Hour Components
Use the hour property to extract the hour component from Period objects ?
import pandas as pd
# Create Period objects
period1 = pd.Period("2020-09-23 05:55:30")
period2 = pd.Period(freq="H", year=2021, month=7, day=16, hour=2, minute=35)
period3 = pd.Period("2023-12-31 23:45:00")
# Extract hour components
hour1 = period1.hour
hour2 = period2.hour
hour3 = period3.hour
print("Hour from period1 (05:55:30):", hour1)
print("Hour from period2 (02:00):", hour2)
print("Hour from period3 (23:45:00):", hour3)
Hour from period1 (05:55:30): 5 Hour from period2 (02:00): 2 Hour from period3 (23:45:00): 23
Working with Period Arrays
You can also extract hours from multiple Period objects at once using PeriodIndex ?
import pandas as pd
# Create a PeriodIndex with multiple periods
periods = pd.PeriodIndex([
"2023-01-01 08:30:00",
"2023-01-01 14:15:30",
"2023-01-01 20:45:15"
], freq='S')
print("Periods:")
print(periods)
print("\nHours:")
print(periods.hour)
Periods:
PeriodIndex(['2023-01-01 08:30:00', '2023-01-01 14:15:30',
'2023-01-01 20:45:15'],
dtype='period[S]')
Hours:
Int64Index([8, 14, 20], dtype='int64')
Key Points
- The
hourproperty returns an integer from 0 to 23 - Works with Period objects created from datetime strings or individual components
- Can be applied to single Period objects or PeriodIndex arrays
- The frequency parameter doesn't affect the hour extraction
Conclusion
The period.hour property provides a simple way to extract hour components from Pandas Period objects. It returns integer values from 0-23 and works with both individual periods and period arrays.
Advertisements
