Get date from week number

Ali SAID OMAR picture Ali SAID OMAR · Jun 13, 2013 · Viewed 67.6k times · Source

Please what's wrong with my code:

import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d, "%Y-W%W")
print(r)

Display "2013-01-01 00:00:00", Thanks.

Answer

Martijn Pieters picture Martijn Pieters · Jun 13, 2013

A week number is not enough to generate a date; you need a day of the week as well. Add a default:

import datetime
d = "2013-W26"
r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w")
print(r)

The -1 and -%w pattern tells the parser to pick the Monday in that week. This outputs:

2013-07-01 00:00:00

%W uses Monday as the first day of the week. While you can pick your own weekday, you may get unexpected results if you deviate from that.

See the strftime() and strptime() behaviour section in the documentation, footnote 4:

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

Note, if your week number is a ISO week date, you'll want to use %G-W%V-%u instead! Those directives require Python 3.6 or newer.