Extracting Date from Week Number
When attempting to retrieve a date from a week number using the following code:
import datetime d = "2013-W26" r = datetime.datetime.strptime(d, "%Y-W%W") print(r)
an error occurs because a week number alone is insufficient to generate a specific date. To resolve this, a specific day of the week must also be specified.
Modify the code by adding a default day of the week, such as Monday, to the string:
import datetime d = "2013-W26" r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w") print(r)
The -1 and -%w patterns in the format string instruct the parser to select the Monday within the specified week. This updated code now correctly outputs:
2013-07-01 00:00:00
It is important to note that the %W directive assumes Monday as the first day of the week in accordance with the strftime() and strptime() behavior outlined in the documentation. Any deviation from this assumption may lead to unexpected results.
For cases where the week number is an ISO week date, the %G-W%V-%u format should be used instead. However, this requires Python version 3.6 or later.
The above is the detailed content of How to Extract a Date from a Week Number in Python?. For more information, please follow other related articles on the PHP Chinese website!