1

I am trying to convert dates in the form Year-WeekNumber to datetimes using strptime. According to the docs I should do it with the formatting code %Y-%W, however when I do this it always returns January 1st.

>>> datetime.datetime.strptime('2020-11', '%Y-%W')
datetime.datetime(2020, 1, 1, 0, 0)
>>> datetime.datetime.strptime('2020-1', '%Y-%W')
datetime.datetime(2020, 1, 1, 0, 0)
>>> datetime.datetime.strptime('2020-31', '%Y-%W')
datetime.datetime(2020, 1, 1, 0, 0)

Why does strptime give the wrong output? Is there another method I can use to handle this conversion?

Edit: Note the suggested question Python - Get date from day of week, year, and week number doesn't fit as it doesn't explain why %Y-%W wasn't suitable for converting and the input syntax it was using was different.

Further Reading
  • 233
  • 2
  • 8

1 Answers1

1

This is not a bug. As you can see in the documentation on strftime() and strptime() format codes, there are two notes next to %W. Here, note (7) is relevant.

  1. When used with the strptime() method, %U and %W are only used in calculations when the day of the week and the calendar year (%Y) are specified.

Therefore, you also have to include a day of the week somewhere in your date, otherwise the date is ambiguous. You can include a weekday with %w:

Directive Meaning Example
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, …, 6

For example, if you always want to select the Monday of the desired week, you can adapt your code as follows:

>>> import datetime
>>> datetime.datetime.strptime('2020-11-1', '%Y-%W-%w')
datetime.datetime(2020, 3, 16, 0, 0)
>>> datetime.datetime.strptime('2020-1-1', '%Y-%W-%w')
datetime.datetime(2020, 1, 6, 0, 0)
>>> datetime.datetime.strptime('2020-31-1', '%Y-%W-%w')
datetime.datetime(2020, 8, 3, 0, 0)

You can make a simple function to return the Monday based on a Year-WeekNumber input:

def get_monday_datetime(week):
    return datetime.datetime.strptime('%s-1' % week, '%Y-%W-%w')
luuk
  • 1,630
  • 4
  • 12
  • Thanks for the clarification! Was expecting it'd error like when %V is used if the syntax was considered incomplete. Fixed it with `datetime.datetime.strptime(f'{week}-1', '%Y-%W-%w')` – Further Reading Mar 15 '21 at 11:56