[Tutor] datetime: inverse of datetime.date.isocalendar()

Zachary Ware zachary.ware+pytut at gmail.com
Fri Jul 12 21:29:07 CEST 2013


On Fri, Jul 12, 2013 at 11:52 AM, elmar werling <elmar at net4werling.de> wrote:
>
> Hello,
>
> how to convert the tuble (iso_year, iso_week, iso_day) to a date object?
>
> I have tried the following scipt, but the results are buggy
>
>
> import datetime
>
> date_i = datetime.date(2013, 07, 12)
> date_iso = date_i.isocalendar()
>
> year = str(date_iso[0])[2:]
> week = str(date_iso[1])
> day = str(date_iso[2])
>
> date_string = year + week + day
> date_ii = datetime.datetime.strptime(date_string,'%y%W%w').date()
>
> print date_i, date_iso, date_string, date_ii
>
>
> Any help is wellcome.
>
> Elmar


It looks like you're seeing a conflict between the way ISO8601 and the
%W format code count weeks.  See here:

>>> today = datetime.date.today()
>>> today
datetime.date(2013, 7, 12)
>>> today.isocalendar()
(2013, 28, 5)
>>> today.strftime('(%Y, %W, %w)')
'(2013, 27, 5)'

If you change your above 'week = ...' line to 'week = str(date_iso[1]
- 1)', you'll get your expected result...this year.  It'll also work
next year, but 2015 will be a different issue entirely with
day-of-week problems.  Then, in 2016, your current code would work.

The datetime module documentation[1] has a lot of good information and
a couple of very informative links.

HTH

--
Zach

[1] http://docs.python.org/2.7/library/datetime


More information about the Tutor mailing list