1

Following answers to this https://stackoverflow.com/questions/2600775/how-to-get-week-number-in-python, I was using datetime.isocalendar(), and more specifically datetime.isocalendar()[1] to get the week number, for instance:

import datetime as dt
dt.date(2015, 10, 16).isocalendar()[1]
>>> 42

Which is fine at a glance, except that result is different from:

dt.date(2015, 10, 16).strftime('%W')
>>> '41'

One can argue that it is fine as long as the 1-week different between the 2 methos is consistent for all dates.

But a major issue strikes for some end-of-the year dates, for instance:

dt.date(2018, 12, 31).isocalendar()[1]
>>> 1

dt.date(2018, 12, 31).strftime('%W')
>>> 53

There is no way I would expect the datetime.isocalendar() method returns week #1 for Dec.31, 2018. Note, it seems that the coder have followed an ISO standard, see here.

How can I somewhat control the behavior?

tagoma
  • 3,896
  • 4
  • 38
  • 57

1 Answers1

1

ISO week has 52 or 53 full weeks. That is 364 or 371 days instead of the usual 365 or 366 days.

ISO uses a special algorithm. You can read more here. So it has advantages like all weeks have exactly 7 days and every week belongs to a single year.

Using one of the types depends on the tasks you solve.