Batu Lab NotesPractical developer guides

Find an ISO week label for a reporting date

By Batu ยท English technical notes

Also published in our Blogger archive.

A reporting week label should use ISO calendar fields instead of combining date.year with a week number from another convention. ISO week years can differ from Gregorian calendar years near New Year. For example, December 30, 2024 belongs to ISO week 1 of ISO year 2025, so the correct label is 2025-W01, not 2024-W01.

The function receives a date, calls isocalendar(), and formats the returned year and week with a two-digit week number. Python documents that isocalendar() returns a named tuple with year, week, and weekday; using its named attributes avoids relying on positional indexes. The assertions test a cross-year boundary and an ordinary midyear date. They establish the expected labels for those inputs, but they do not choose a fiscal calendar or define which timezone should turn an incoming timestamp into a reporting date.

This API exists in Python 3.2 and later. In Python 3.9 and later, the result is the named tuple represented by datetime.IsoCalendarDate, so the attribute access shown here is supported on currently maintained Python versions. ISO week labels are appropriate only when consumers agree on ISO 8601 week conventions. Read the official date.isocalendar() documentation for its fields and calendar definition.

AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.

from datetime import date


def iso_week_label(reporting_date: date) -> str:
    iso = reporting_date.isocalendar()
    return f"{iso.year}-W{iso.week:02d}"


boundary_date = date(2024, 12, 30)
assert iso_week_label(boundary_date) == "2025-W01"
assert iso_week_label(date(2025, 7, 2)) == "2025-W27"

print(iso_week_label(boundary_date))
2025-W01