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)
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.
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.
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.
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.
With the isoweek module you can do it with:
from isoweek import Week d = Week(2011, 40).monday()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With