Explain Codes LogoExplain Codes Logo

How to get week number in Python?

python
datetime
strftime
pandas
Nikita BarsukovbyNikita Barsukov·Oct 18, 2024
TLDR

Here's your quick fix to fetch the week number using Python's datetime module:

from datetime import datetime # Who knows the week number, really? # Good thing Python does! print(datetime.now().isocalendar().week)

This chunk of code prints out the present week number adhering to the ISO 8601 standard (i.e., weeks start on Monday). And from Python 3.9 onwards, you can fetch it directly using .week.

Week number: a deep dive

Ever scratched your head trying to calculate which week of the year today is? Fear not, Python is here to save your day (and week)!

Week numbering: rules of the game

Even though Python defaults to the ISO 8601 week definition starting on Monday, there are alternative systems:

  • %U: Week starts on Sunday (range: 00-53)
  • %W: Week starts on Monday (range: 00-53)
  • %V: ISO 8601 week number (range: 01-53)

You can access these using the strftime function:

date_obj = datetime.now() print("Sunday as start:", date_obj.strftime("%U")) print("Monday as start (yeah, it hurts!):", date_obj.strftime("%W")) print("ISO 8601 week number:", date_obj.strftime("%V"))

Leap years: no leaping over them!

Python takes care of leap years as easily as you leap over a puddle. datetime ensures that week numbers are calculated accurately across all year types.

Specific date into week number

Want to know the week number of a specific date? First, parse the string into a date object:

from datetime import datetime date_string = "2023-04-14" # Just a random date date_obj = datetime.strptime(date_string, "%Y-%m-%d") # Transform it to a date object week_number = date_obj.isocalendar().week # Magic! print(f'We're in week number {week_number} on {date_string}')

Less known week numbering

For niche needs such as epidemiological week numbers (like in CDC reports), you may require libraries like epiweeks. Not your usual tea, but tastes good if you need it!

Calendar explorers

Let's journey across different dates:

# Comparing April 14 across various years dates = ['2021-04-14', '2022-04-14', '2023-04-14'] for date in dates: date_obj = datetime.strptime(date, "%Y-%m-%d") week_number = date_obj.isocalendar().week print(f'Year changes, house changes! {date} is at week {week_number}.')

Watch your step: edge cases!

Beware near the year switching corners. Week 1 of any year includes January 4th or the first week with majority of its days in the starting year.

Quick fixes for large data

If you're working with a ton of dates, efficient libraries like numpy or pandas are your friends. They say pandas eat a lot, but they compute faster too!