[Tutor] datetime: inverse of datetime.date.isocalendar()
Jerry Hill
malaclypse2 at gmail.com
Fri Jul 12 21:34:50 CEST 2013
On Fri, Jul 12, 2013 at 12:52 PM, 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
You can't feed the ISO week number and ISO day-of-week into strptime
as-is. They just don't represent the same values. There's more of an
explanation in the docs, here
http://docs.python.org/2/library/datetime.html#datetime.date.isocalendar
.
I'm having a hard time summarizing, but the basic difference between
the ISO calendar and the C strptime() definitions seems to be how they
define the week of the year. In the ISO Calendar, the first week of
the year is the first week where a thursday occurs in the week. In
the C-style '%W' week-of-year format specifier, I believe the first
week of the year is based on where the first monday falls, instead.
Let's see if I can come up with an example or two.
>>> import datetime
>>> jan_1_2013 = datetime.date(2013, 1, 1)
>>> jan_1_2013.isocalendar()
(2013, 1, 2)
So, in the ISO calendar, this is 2013, week 1, day 2.
>>> datetime.datetime.strftime(jan_1_2013, "%Y %W %w")
'2013 00 2'
In the C-style strptime() world, this same date is 2013, week 0, day 2.
Does that help explain why your original attempt was exactly one week
(7 days) off what you thought it should be?
--
Jerry
More information about the Tutor
mailing list