Search code examples
pythonstrptime

How can I get the date from weeknr and year using strptime


I'm trying to get the date of monday given some weeknr and year. But I feel like strptime is just returning the wrong date. This is what I try:

from datetime import date, datetime

today = date.today()
today_year = today.isocalendar()[0]
today_weeknr = today.isocalendar()[1]
print(today)
print(today_year, today_weeknr)

d = "{}-W{}-1".format(today_year, today_weeknr)
monday_date = datetime.strptime(d, "%Y-W%W-%w").date()
print(monday_date)
print(monday_date.isocalendar()[1])

Result:

$ python test.py 
2025-02-13
2025 7
2025-02-17
8

So how the hell am I in the next week now?


Solution

  • There was an answer here before, but it got removed. I don't know why.

    The issue is that I was taking the weeknr from the isocalendar and later was parsing the isocalendar week,year into a date with non isocalendar directives.

    "%Y-W%W-%w" takes:

    • %Y Year with century as a decimal number.
    • %W Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0
    • %w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

    The solution for was to just use the iso directives:

    d = "{}-{}-1".format(year, weeknr)
    monday_date = datetime.strptime(d, "%G-%V-%u").date()
    
    • %G ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V).
    • %V ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.
    • %u ISO 8601 weekday as a decimal number where 1 is Monday.

    Clearly if you use isocalendar() to get the week and year, you also need ISO directives to parse it back to a date.