Python
3.8添加了fromisocalendar()方法:
>>> datetime.fromisocalendar(2011, 22, 1)datetime.datetime(2011, 5, 30, 0, 0)
Python的3.6添加的
%G,
%V并
%u指示:
>>> datetime.strptime('2011 22 1', '%G %V %u')datetime.datetime(2011, 5, 30, 0, 0)
原始答案
我最近不得不自己解决此问题,并提出了以下解决方案:
import datetimedef iso_year_start(iso_year): "The gregorian calendar date of the first day of the given ISO year" fourth_jan = datetime.date(iso_year, 1, 4) delta = datetime.timedelta(fourth_jan.isoweekday()-1) return fourth_jan - deltadef iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1)
一些测试用例:
>>> iso = datetime.date(2005, 1, 1).isocalendar()>>> iso(2004, 53, 6)>>> iso_to_gregorian(*iso)datetime.date(2005, 1, 1)>>> iso = datetime.date(2010, 1, 4).isocalendar() >>> iso(2010, 1, 1)>>> iso_to_gregorian(*iso)datetime.date(2010, 1, 4)>>> iso = datetime.date(2010, 1, 3).isocalendar()>>> iso(2009, 53, 7)>>> iso_to_gregorian(*iso)datetime.date(2010, 1, 3)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)