Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date from ISO week number in Python [duplicate]

Possible Duplicate:
What’s the best way to find the inverse of datetime.isocalendar()?

I have an ISO 8601 year and week number, and I need to translate this to the date of the first day in that week (Monday). How can I do this?

datetime.strptime() takes both a %W and a %U directive, but neither adheres to the ISO 8601 weekday rules that datetime.isocalendar() use.

Update: Python 3.6 supports the %G, %V and %u directives also present in libc, allowing this one-liner:

>>> datetime.strptime('2011 22 1', '%G %V %u') datetime.datetime(2011, 5, 30, 0, 0) 

Update 2: Python 3.8 added the fromisocalendar() method, which is even more intuitive:

>>> datetime.fromisocalendar(2011, 22, 1) datetime.datetime(2011, 5, 30, 0, 0) 
like image 684
Erik Cederstrand Avatar asked May 04 '11 11:05

Erik Cederstrand


People also ask

How do you convert a week to a date in Python?

To get date from week number with Python, we can use the datetime strptime method. 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.

How do I convert ISO to date in Python?

To translate an ISO 8601 datetime string into a Python datetime object, we can use the dateutil parser. parse method. to call parser. parse with date_string to convert the ISO 8601 date_string into the your_date datetime object.

How do I get the day of the week number in Python?

isoweekday() to get a weekday of a given date in PythonUse the isoweekday() method to get the day of the week as an integer, where Monday is 1 and Sunday is 7. i.e., To start from the weekday number from 1, we can use isoweekday() in place of weekday() . The output is 1, which is equivalent to Monday as Monday is 1.

How do I print week numbers in Python?

YOu can use the isocalender function from the datetime module to get the current week. Create the object of the date first, then call isocalender() on this object. This returns a 3-tuple of Year, Week number and Day of Week.


1 Answers

With the isoweek module you can do it with:

from isoweek import Week d = Week(2011, 40).monday() 
like image 121
gisle Avatar answered Sep 19 '22 18:09

gisle