What’s the best way to find the inverse of datetime.isocalendar()?
>>> datetime.strptime('2011 22 1', '%G %V %u')
datetime.datetime(2011, 5, 30, 0, 0)
%W takes the first Monday to be in week 1 but ISO defines week 1 to contain 4 January. So the result from
is off by one iff the first Monday and 4 January are in different weeks. The latter is the case if 4 January is a Friday, Saturday or Sunday. So the following should work:
from datetime import datetime, timedelta, date def tofirstdayinisoweek(year, week): ret = datetime.strptime('%04d-%02d-1' % (year, week), '%Y-%W-%w') if date(year, 1, 4).isoweekday() > 4: ret -= timedelta(days=7) return ret