Open In App

Pandas Series dt.month | Extract Month Part From DateTime Series

Improve
Improve
Like Article
Like
Save
Share
Report

The dt.month attribute returns a NumPy array containing the month 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.month
print(result)


Output:

month value of datetime

Syntax

Syntax: Series.dt.month 

Parameter : None 

Returns: NumPy array with month values of DateTime object

How to Extract Month Value From DateTime Object in Pandas Series

To extract the month value from the DateTime object we use the Series.dt.month attribute of the Pandas library in Python

Let us understand it better with an example:

Example:

Use the Series.dt.month attribute of Pandas library to return the month of the DateTime in the underlying data of the given Series object.

Python3




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(pd.date_range('2012-12-12 12:12',
                       periods = 5, freq = 'H'))
  
# Creating the index
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
  
# set the index
sr.index = idx
  
# Print the series
print(sr)


Output :

time series created

Now we will use the Series.dt.month attribute to return the month of the DateTime in the underlying data of the given Series object.

Python3




# return the month
result = sr.dt.month
  
# print the result
print(result)


Output :

month values of datetime

As we can see in the output, the Series.dt.month attribute has successfully accessed and returned the month of the DateTime in the underlying data of the given series object.



Last Updated : 06 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads