Extract Hour from DatetimeIndex in Python Pandas



To extract hour from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.hour property.

At first, import the required libraries −

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...\n", datetimeindex)

Get the hour −

print("\nGetting the hour..\n",datetimeindex.hour)

Example

Following is the code −

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...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# get the hour
print("\nGetting the hour..\n",datetimeindex.hour)

Output

This will produce the following code −

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')
Updated on: 2021-10-18T11:06:44+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements