Pythondatetime.isocalendar()方法返回(ISO_year, ISO_week_number, ISO_weekday)给定datetime对象的元组。有相应的逆函数吗?如果不是,是否有一种简单的方法来计算给定的年份,星期数和星期几?
datetime.isocalendar()
(ISO_year, ISO_week_number, ISO_weekday)
datetime
Python 3.8添加了fromisocalendar()方法:
>>> datetime.fromisocalendar(2011, 22, 1) datetime.datetime(2011, 5, 30, 0, 0)
Python的3.6添加的%G,%V并%u指示:
%G
%V
%u
>>> datetime.strptime('2011 22 1', '%G %V %u') datetime.datetime(2011, 5, 30, 0, 0)
原始答案
我最近不得不自己解决此问题,并提出了以下解决方案:
import datetime def 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 - delta def 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)