How to Extract Week From DateTime Series
To extract the week value from the DateTime series we use the Series.dt.week attribute of the Pandas library in Python.
Let us understand it better with an example:
Example:
Use the Series.dt.week attribute to return the week ordinal of the year 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 = 'M' )) # 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 :
Now we will use the Series.dt.week attribute to return the week ordinal of the year in the underlying data of the given Series object.
Python3
# return the week ordinal # of the year result = sr.dt.week # print the result print (result) |
Output :
As we can see in the output, the Series.dt.week attribute has successfully accessed and returned the week ordinal of the year in the underlying data of the given series object.
Pandas Series dt.week | Extract Week Number from DateTime Series
Pandas dt.week attribute returns a NumPy array containing the week ordinal of the year in the underlying data of the given DateTime Series object.