The datetime
module provides a method date.isocalendar
that, given a date, returns it in the format ([year], [week], [weekday])
. How do I go backwards? Given a ([year], [week], [weekday])
tuple, how can I get a date
object?
Asked
Active
Viewed 7,252 times
8

Ram Rachum
- 84,019
- 84
- 236
- 374
-
Hot d*mn, this is more complicated than I thought at first. Week 1 is the week that contains the calendar year's first *Thursday*!?! – Tim Pietzcker Mar 02 '11 at 16:24
-
3Haha. Welcome to the world of calendars, enjoy your stay :) – Ram Rachum Mar 02 '11 at 16:27
-
1I have a nagging suspicion that there's a very good reason why this function is not in the Standard Library :) – Tim Pietzcker Mar 02 '11 at 16:31
1 Answers
4
EDIT Found question with solution: What's the best way to find the inverse of datetime.isocalendar()?
My solution had mistakes. On googling saw previous question which upon testing below worked. (See top answered question in above link for definition of iso_to_gregorian
). (Basically find iso year start date and then use timedelta to find current date from day and week number.
for i in range(-10000,10000,1):
x = datetime.datetime.today().date() + datetime.timedelta(i)
x_iso = datetime.datetime.isocalendar(x)
assert iso_to_gregorian(*x_iso) == x
-
3
-
1Yup as soon as I tested it I realized I had mistakes. Discussion on 2008 stackoverflow question goes through the reasons the edge cases weren't working and has a relatively simple solution. – dr jimbob Mar 02 '11 at 16:38
-
-