Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strptime seems to create wrong date from week number

strptime seems to create wrong date from week number...

First case :

dt1 =  dateutil.parser.parse('2016-01-04 00:00:00+01:00')
dt1.isocalendar()
=> (2016, 1, 1) # (year, week number, week day)

from datetime import datetime
datetime.strptime('2016 1 1', '%Y %W %w')
=> datetime.datetime(2016, 1, 4, 0, 0)
# OK

Second case :

dt1 =  dateutil.parser.parse('2015-12-28 00:00:00+01:00')
dt1.isocalendar()
=> (2015, 53, 1) # (year, week number, week day)

datetime.strptime('2015 53 1', '%Y %W %w')
=> datetime.datetime(2016, 1, 4, 0, 0)
# Should return datetime.datetime(2015, 12, 28, 0, 0)

What's wrong ?

like image 884
Aurélien Avatar asked Mar 14 '23 10:03

Aurélien


1 Answers

strptime %W uses the regular calendar weeks. The ISO week date is different from the regular calendar. Years are divided into 52 or 53 weeks exactly (364 or 371 days).

Currently python's strptime does not support iso week dates, but it is planned for python 3.6. Then you can use %G %V %w (I think) to parse iso week dates. http://bugs.python.org/issue12006

Until then you can use the isoweek package to parse iso week dates. https://pypi.python.org/pypi/isoweek/

like image 152
Håken Lid Avatar answered Mar 25 '23 01:03

Håken Lid