What's the best way to find the inverse of datetime.isocalendar()?

Viewed 17503

The Python datetime.isocalendar() method returns a tuple (ISO_year, ISO_week_number, ISO_weekday) for the given datetime object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?

8 Answers

Note that %W is the week # (0-53) which is NOT THE SAME as the ISO week (1-53). There will be edge cases where %W will not work.

I came up with a solution similar to the one posted by Ben James, but using a single function:

import datetime
def getDateFromWeek(year,week,day):
    """Method to retrieve the date from the specified week, year and weekday"""

    year_start = datetime.date(year,1,1)
    ys_weekday =  year_start.weekday()
    delta = (week*7)+(day-ys_weekday)
    if ys_weekday<4:
        delta -= 7

    return  year_start  + datetime.timedelta(days=delta)

I tested it out with boundary values such as the last week of 2020 and first week of 2021, and it worked out pretty well.

EDIT: ignore this, the edge cases are a pain. Go with Ben's solution.

Ok, on closer inspection I noticed that strptime has %W and %w parameters, so the following works:

def fromisocalendar(y,w,d):
   return datetime.strptime( "%04dW%02d-%d"%(y,w-1,d), "%YW%W-%w")

A couple of gotchas: The ISO week number starts at 1, while %W starts at 0. The ISO week day starts at 1 (Monday), which is the same as %w, so Sunday would probably have to be 0, not 7...

Related