Categories
Python Answers

How to get date from week number with Python?

Spread the love

Sometimes, we want to get date from week number with Python.

In this article, we’ll look at how to get date from week number with Python.

How to get date from week number with Python?

To get date from week number with Python, we can use the datetime strptime method.

For instance, we write

import datetime

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

to call strptime with the d string with '-1' appended to it.

Then we parse the date string as a string with format "%Y-W%W-%w".

%Y is the 4 digit year.

W%W is the week number. %w is the date of the week as a number.

1 is Monday and strptime use that as the first day of the week.

Conclusion

To get date from week number with Python, we can use the datetime strptime method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *