Home > Article > Backend Development > Why Does Converting Week Numbers to Dates in Python Fail with "2013-W26"?
Converting Week Numbers to Dates
You've encountered an issue while attempting to convert a week number to a date using the following code:
import datetime d = "2013-W26" r = datetime.datetime.strptime(d, "%Y-W%W") print(r)
When executing this code, you expected to see "2013-01-01 00:00:00", but instead, you encountered an error. Let's explore what's causing this and how to resolve it.
Addressing the Issue
To accurately convert a week number to a date, you require additional information beyond the week number itself, namely, the day of the week. Adding a default day of the week to your code will address this issue. Here's the modified code:
import datetime d = "2013-W26" r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w") print(r)
Explanation of the Modification
The ' -1' and '-%w' pattern additions are crucial in this modification. The '-1' tells the parser to pick Monday in that particular week, and the '-%w' adjusts the day of the week relative to Monday. For instance, using '-%w' would return Sunday if the supplied week number corresponds to Monday.
Behavior of %W and Footnote 4
In the Python documentation's strftime() and strptime() behavior section, footnote 4 provides valuable insight: "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."
Additional Notes
If you're dealing with an ISO week date, you can utilize %G-W%V-%u instead. These directives require Python 3.6 or later.
The above is the detailed content of Why Does Converting Week Numbers to Dates in Python Fail with "2013-W26"?. For more information, please follow other related articles on the PHP Chinese website!