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
Python Pandas - Extract the hour from the DateTimeIndex with specific time series frequency
To extract hour from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.hour property. This is particularly useful when working with time series data that has hourly frequency patterns.
Creating DateTimeIndex with Hourly Frequency
First, let's create a DateTimeIndex with hourly frequency using pd.date_range() ?
import pandas as pd
# DatetimeIndex with period 6 and frequency as H i.e. hour
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')
# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-20 03:35:55+11:00',
'2021-10-20 04:35:55+11:00', '2021-10-20 05:35:55+11:00',
'2021-10-20 06:35:55+11:00', '2021-10-20 07:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='H')
Extracting Hours from DateTimeIndex
Use the .hour property to extract hour values from each timestamp ?
import pandas as pd
# DatetimeIndex with period 6 and frequency as H i.e. hour
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:35:55', periods=6, tz='Australia/Sydney', freq='H')
# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)
# Display DateTimeIndex frequency
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)
# Get the hour
print("\nGetting the hour...")
print(datetimeindex.hour)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:35:55+11:00', '2021-10-20 03:35:55+11:00',
'2021-10-20 04:35:55+11:00', '2021-10-20 05:35:55+11:00',
'2021-10-20 06:35:55+11:00', '2021-10-20 07:35:55+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='H')
DateTimeIndex frequency...
<Hour>
Getting the hour...
Int64Index([2, 3, 4, 5, 6, 7], dtype='int64')
Key Points
The DateTimeIndex.hour property returns an Int64Index containing the hour values (0-23) for each timestamp in the DateTimeIndex. This is useful for filtering, grouping, or analyzing data by hourly patterns.
Conclusion
The DateTimeIndex.hour property provides an efficient way to extract hour components from datetime data. This is especially valuable when working with time series data that requires hourly analysis or filtering.
