从Python中的ISO周编号获取日期 [英] Get date from ISO week number in Python
问题描述
Possible Duplicate:
What’s the best way to find the inverse of datetime.isocalendar()?
我有一个ISO 8601年和周号,我需要将其转换为该周第一天的日期(星期一).我该怎么办?
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()同时使用%W
和%U
指令,但均未遵循
datetime.strptime() takes both a %W
and a %U
directive, but neither adheres to the ISO 8601 weekday rules that datetime.isocalendar() use.
更新: Python 3.6 支持libc中也存在的%G
,%V
和%u
指令,从而允许这种单行代码:
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)
更新2 : Python 3.8 添加了fromisocalendar()
方法,该方法更加直观:
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)
推荐答案
%W将第一个星期一设为第1周,但ISO将第1周定义为包含1月4日.所以结果来自
%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')
如果在不同的一周的第一个星期一和1月4日,
关闭. 如果1月4日是星期五,星期六或星期日,则后者是这种情况. 因此,以下方法应该起作用:
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
这篇关于从Python中的ISO周编号获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!