1

I am using Python 2.7 and I am trying to convert week numbers to actual dates.

I was using this solution which worked fine for basics tests, but I found a case where there seems to be a break: in years with 53 weeks.

The example below shows the issue:

datetime.datetime.strptime( "2015-W53-0", "%Y-W%W-%w").strftime("%Y-W%W-%w")

This returns '2016-W01-0', which I think does not make sense.

Is this a known issue, is there a known workaround?

Note that:

datetime.datetime.strptime( "2015-W53-0", "%Y-W%W-%w").isocalendar()

yields (2016, 1, 7), so it's probably strptime which is guessing wrong here.

Community
  • 1
  • 1
SRKX
  • 1,806
  • 1
  • 21
  • 42

2 Answers2

2

I actually found a good library called isoweek which works as I expect.

#This is Week 53 of 2015 according to ISO
week = isoweek.Week.withdate( datetime.date( 2016,1,1) )
monday = week.monday()
print monday.isocalendar()
#Prints (2015, 53, 1), which is correct.

I think this is the simplest way to handle these issues.

SRKX
  • 1,806
  • 1
  • 21
  • 42
  • This works, thanks for posting the solution. You might accept your own answer for this question. It's a shame that `strptime` doesn't support the `%G` and `%V` for ISO dates *James K* mentions (at least not in Python 3.5.2). – JeroenHoek Nov 03 '17 at 20:00
1

%W is the week of the year, with the first week containing a Monday counted as week 1.

The first day of the week is Monday, which has a %w day number of 1. The last day of the week is Sunday, which has a day number of 0. So in this reckoning %Y-%W-0 always comes six days later than %Y-%W-1.

By this reckoning, the 52nd week starts on the 28th of December, and doesn't contain a Sunday. So 2015-W52-0 is interpreted as the first Sunday in 2016 (Jan 3rd). Since this is before the first Monday, 2015-W52-0 is canonically 2016-W00-0 and 2015-W53-0 is the second Sunday in 2016, which is at the end of week 1, ie Jan 10th, or 2016-W01-0.

So the methods are working as documented.

The %W and %w don't implement the ISO week date algorithm, which sets the first week as that containing a Thursday. 2015 contains a 53rd week by the ISO method, but not by the %W method. If you want to use ISO weekdates you should use isocalendar.

Since the standard implementation of python is just calling the C library functions, you may be able to use %G (The year) and %V (the week number) according to the ISO algorithm. But these can't be guaranteed to be portable.

James K
  • 3,692
  • 1
  • 28
  • 36