Use the ISO week year in Python weekly report keys
A weekly report near New Year can belong to a different ISO year from its calendar date. Combining date.year with an ISO week number creates misleading labels at that boundary.
Run the example
Tested on Linux with Python 3.12.14 and Python 3.13.5. Use one Bash session and a text editor. Create a disposable working directory before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save as demo_python_iso_week_year_report_keys.py:
from datetime import date
for day in (date(2020, 12, 31), date(2021, 1, 1), date(2021, 1, 4)):
year, week, weekday = day.isocalendar()
key = f"{year}-W{week:02d}"
monday = date.fromisocalendar(year, week, 1)
assert date.fromisocalendar(year, week, weekday) == day
print(f"{day}: {key}, Monday={monday}")
try:
date.fromisocalendar(2021, 53, 1)
except ValueError:
print("2021-W53: rejected")
else:
raise AssertionError("invalid ISO week accepted")Run it:
python3 -B demo_python_iso_week_year_report_keys.pyObserved output:
2020-12-31: 2020-W53, Monday=2020-12-28
2021-01-01: 2020-W53, Monday=2020-12-28
2021-01-04: 2021-W01, Monday=2021-01-04
2021-W53: rejectedJanuary 1, 2021 belongs to the final ISO week of 2020. The key uses both the year and week returned by isocalendar(). fromisocalendar() recovers the Monday of that week and validates whether a proposed week exists.
Limits and input policy
ISO weeks start on Monday, and week one contains the first Thursday of the ISO year. Some years have 53 weeks, but 2021 does not. This example starts from dates. For timestamped events, first choose the reporting time zone and obtain the local date; a UTC date and a business-local date can fall into different weeks.
Clean up
Remove the saved script and the empty working directory in the same Bash session:
rm -- demo_python_iso_week_year_report_keys.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before removing anything else.
Reference
Acknowledgements
This post was created with assistance from AI.