How to Extract a Date from a Week Number in Python?

Barbara Streisand
Release: 2024-11-10 20:52:02
Original
943 people have browsed it

How to Extract a Date from a Week Number in Python?

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)
Copy after login

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template