brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ISO week numbers need %G and %V, or date.isocalendar()

Linux
~/tips/tip-python-isocalendar-iso-week

python3 -c "import datetime as d; print(d.date(2027,1,1).isocalendar())"

Gets ISO 8601 week dates right at the turn of the year, in Python and with GNU date.

Week numbers are fine until the last days of December. Then 1 January 2027 turns out to belong to week 53 of 2026, and a calendar year plus a week number gives a wrong label.

python3 -c "import datetime as d; print(d.date(2027,1,1).isocalendar())"
datetime.IsoCalendarDate(year=2026, week=53, weekday=5)

The Python docs explain why. The ISO year has 52 or 53 full weeks, each starting on Monday, and week 1 is the first week that contains a Thursday. So a few days around New Year can belong to the neighbouring ISO year. date.isocalendar() returns year, week and weekday as a named tuple (a plain tuple before Python 3.9), and date.fromisocalendar(2026, 53, 4) converts back, which gives 31 December 2026. That one needs Python 3.8 or newer.

For a string, GNU date has the same directives. Its help lists %G as the year of the ISO week number, %V as the ISO week number and %u as the day of the week from 1 (Monday). On GNU date 9.4:

date -d 2027-01-01 +'%G-W%V-%u %j'
2026-W53-5 001

Python’s strftime("%G-W%V-%u") gave the same style of result, for example 2026-W53-1 for 28 December 2026.

The caveat is the one directive people reach for out of habit. %Y is the calendar year, which for that day is 2027, so %Y-W%V printed 2027-W53 there, a label for a week that does not exist. The GNU help itself says %G is normally useful only together with %V. If a report groups by week, use the pair, or the tuple from isocalendar().

Further reading: Python datetime: isocalendar, GNU coreutils: date invocation

More Linux tips notify-send -r "$id" "Backup" "Done" pgrep -af 'sleep 301' smbstatus -L msmtp --serverinfo --tls --tls-certcheck=off --host=smtp.example.com --port=587 smbclient //server/share -U user -Tc backup.tar "*" All Linux tips (283) All topics

Link