Get date from ISO week number in Python [duplicate]

半城伤御伤魂 提交于 2019-11-26 09:44:12

问题


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)

回答1:


%W takes the first Monday to be in week 1 but ISO defines week 1 to contain 4 January. So the result from

datetime.strptime('2011221', '%Y%W%w')

is off by one iff the first Monday and 4 January are in different weeks. The latter is the case if 4 January is a Friday, Saturday or Sunday. So the following should work:

from datetime import datetime, timedelta, date
def tofirstdayinisoweek(year, week):
    ret = datetime.strptime('%04d-%02d-1' % (year, week), '%Y-%W-%w')
    if date(year, 1, 4).isoweekday() > 4:
        ret -= timedelta(days=7)
    return ret



回答2:


With the isoweek module you can do it with:

from isoweek import Week
d = Week(2011, 40).monday()


来源:https://stackoverflow.com/questions/5882405/get-date-from-iso-week-number-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!