Home > Article > Backend Development > How to Determine a Specific Date from a Week Number in Python?
Determining a Date from a Week Number
In Python, using the datetime module to extract a date from a week number requires additional context to accurately determine the specific day. The provided code:
import datetime d = "2013-W26" r = datetime.datetime.strptime(d, "%Y-W%W") print(r)
displays "2013-01-01 00:00:00" because the week number is insufficient to specify a unique date. To resolve this, you need to provide a specific day of the week within that week.
Corrected Code
import datetime d = "2013-W26" r = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w") print(r)
In this corrected code, -1 is added to the week number, effectively indicating the first day of that week (Monday), which is specified by -%w. This outputs "2013-07-01 00:00:00", corresponding to the Monday of the 26th week in 2013.
Formatting Notes
When using %W as the formatting directive, Monday is considered the first day of the week. If a different day of the week is desired, you can use an alternative directive.
ISO Week Date
If the week number provided is in the ISO week date format, which starts on Monday, you should use a different set of formatting directives:
d = "2013-W26" r = datetime.datetime.strptime(d + '-1', "%G-W%V-%u")
These directives require Python 3.6 or later for compatibility.
The above is the detailed content of How to Determine a Specific Date from a Week Number in Python?. For more information, please follow other related articles on the PHP Chinese website!