Gustaf Rosenblad
Gustaf Rosenblad

Reputation: 1922

Python date calculating with year and week of year is incorrect

We are having an issue when calculating the start of the first week in 2019.

The parameters are year and week_of_year. We are always staring the week at Monday.

The code to get the first day of a specific year:

from datetime import datetime

result = datetime.strptime('%04d-%02d-1' % (year, week_of_year), '%Y-%W-%w').date()

This works for most of the years, but not in the case when year = 2019 and week_of_year = 1, Python computes this to the date 2019-01-02 and not the expected 2018-12-31.

Our current solution to solve this problem is:

from datetime import datetime, timedelta

result = datetime.strptime('%04d-%02d-1' % (year, week_of_year), '%Y-%W-%w').date()

# Fixes issue with Python date computing returning the incorrect date
# This only occures for some years. E.g. 2019.
offset = result.isocalendar()[1] - datetime.strptime('%04d-01-01' % year, '%Y-%m-%d').date().isocalendar()[1]
if offset > 0:
    result = result - timedelta(days=7)

Any other ideas on how to fix this issue?

Upvotes: 1

Views: 2745

Answers (1)

SpghttCd
SpghttCd

Reputation: 10860

After consulting https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior, I can tell that %W does not respect ISO-definition of the week counter, but simply counts from the first monday in a year. The days before are put into week count 0...

You can try %V together with %G:

result = datetime.strptime('%04d-%02d-1' % (year, 1), '%G-%V-%w').date()

Upvotes: 3

Related Questions