Pandas Series dt.hour | Extract Hour Part from Time Stamp
Pandas dt.hour attribute returns a NumPy array containing the hour of the DateTime in the underlying data of the given Series object.
Example
Python3
import pandas as pd
sr = pd.Series([ '2012-10-21 09:30' , '2019-7-18 12:30' , '2008-02-2 10:30' ,
'2010-4-22 09:25' , '2019-11-8 02:22' ])
idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ]
sr.index = idx
sr = pd.to_datetime(sr)
result = sr.dt.hour
print (result)
|
Output
Syntax
Syntax: Series.dt.hourÂ
Parameter: NoneÂ
Returns: NumPy array containing hour values
How to Extract Hour from DateTime Object in Pandas Series
To extract the hour value from the DateTime object in the Pandas Series we use the dt.hour attribute of the Pandas library in Python.
Let us understand it better with an example:
Example:
Use the Series.dt.hour attribute to return the hour of the DateTime in the underlying data of the given Series object.
Python3
import pandas as pd
sr = pd.Series(pd.date_range( '2012-12-12 12:12' ,
periods = 5 , freq = 'H' ))
idx = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' , 'Day 5' ]
sr.index = idx
print (sr)
|
Output :
Now we will use the Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object.
Python3
result = sr.dt.hour
print (result)
|
Output :
As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the DateTime in the underlying data of the given series object.
Last Updated :
07 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...