Python get week number from datetime

Being able to get the week number, or year week number, from a DateTime object in Python can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.

How do you get the week number from a datetime object in Python?

In order to get the week number from a datetime object in Python you need to use .isocalendar().week. This is the recommended approach for Python > 3.9. However, for older versions of Python you need to access the second element of the .isocalendar() list instead of using .week.

code for getting week number from python datetime

Python get week number from datetime

Here are the two ways to get the week number from a datetime object, for both newer and older versions of Python.

import datetime

date = datetime.date(2022, 9, 1)

week_number_old = date.isocalendar()[1]
week_number_new = date.isocalendar().week

print(date)
print(f"Old method: Week number {week_number_old}")
print(f"New method: Week number {week_number_new}")

"""
Output:

2022-09-01
Old method: Week number 35
New method: Week number 35
"""

Pandas get week number from datetime

If you’re using Pandas as a way to store your data then you can easily get the week number from a datetime column by using the .dt.week method.

import pandas as pd

df = pd.DataFrame(
	columns=["datetime"],
	data=pd.date_range("1/8/2022 09:00:00", periods=4, freq="D"))

df["week_number"] = df["datetime"].dt.week

"""
Output:

datetime                 week_number
0 2022-01-08 09:00:00    1
1 2022-01-09 09:00:00    1
2 2022-01-10 09:00:00    2
3 2022-01-11 09:00:00    2
"""

Python get year week number from datetime

If you have a dataset that spans multiple years then you may want to return a combination of year and week to make it unique. Here is how this can be done in Python, note that this method assumes that the week starts on a Monday.

import datetime

date = datetime.date(2022, 9, 1)

year_week = date.strftime('%Y-%V')

print(date)
print(f"Year week combination: {year_week}")

"""
Output:

2022-09-01
Year week combination: 2022-35
"""

Pandas get year week number from datetime

It’s also possible to calculate this unique year-week combination for a Pandas dataframe using the same approach.

import pandas as pd

df = pd.DataFrame(
	columns=["datetime"],
	data=pd.date_range("1/8/2022 09:00:00", periods=4, freq="D"))

df["year_week"] = df["datetime"].dt.strftime('%Y-%V') 

"""
Output:

datetime                year_week
0 2022-01-08 09:00:00   2022-01
1 2022-01-09 09:00:00   2022-01
2 2022-01-10 09:00:00   2022-02
3 2022-01-11 09:00:00   2022-02
"""

Python round DateTime to day
Python round DateTime to week
Python round DateTime to start or end of month
Python round DateTime to month
Pandas convert DateTime to date
Python round DateTime to year

References

Python datetime documentation
Pandas datetime documentation

Stephen Allwright

Stephen Allwright

I'm a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I've picked up along the way.
Oslo, Norway