Extract week number from date in Pandas Python

dt.Week  is the inbuilt method for  finding the week number from date in Pandas Python. There is another method to find the week number of the year from date in pandas using strftime() function  Let’s see how to

  • Extract the week number from date in python using dt.week
  • Get week number from date using strftime() function

First lets create the dataframe

import pandas as pd
import numpy as np
import datetime

date1 = pd.Series(pd.date_range('2012-1-1 12:00:00', periods=7, freq='M'))
df = pd.DataFrame(dict(date_given=date1))
print(df)

so the resultant dataframe will be

Get week number from date in Pandas Python (week number of year) 1

 

Get the week number from date in pandas python using dt.week:

Week function gets week number from date. Ranging from 1 to 52 weeks

df['week_number_of_year'] = df['date_given'].dt.week
df

so the resultant dataframe will be

Get week number from date in Pandas Python (week number of year) 2

 

 

Get week number from date using strftime() function:

strftime() function gets week number from date. Ranging from 1 to 52 weeks

df['week_number_of_year'] = df['date_given'].dt.strftime('%U')
df

'%U' represents the week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. so the resultant dataframe will be,

Get week number from date in Pandas Python (week number of year) 2

 

Get week number from date in Pandas Python (week number of year)                                                                                                           Get week number from date in Pandas Python (week number of year)

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts