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:

    The solution for was to just use the iso directives:

    d = "{}-{}-1".format(year, weeknr)
    monday_date = datetime.strptime(d, "%G-%V-%u").date()
    

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