gpt4 book ai didi

python - 找到 datetime.isocalendar() 的倒数的最佳方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 20:37:41 31 4
gpt4 key购买 nike

python datetime.isocalendar()方法为给定的 datetime 对象返回一个元组 (ISO_year, ISO_week_number, ISO_weekday)。有对应的反函数吗?如果没有,是否有一种简单的方法可以计算给定年份、星期数和星期几的日期?

最佳答案

Python 3.8 添加了 fromisocalendar()方法:

>>> datetime.fromisocalendar(2011, 22, 1)
datetime.datetime(2011, 5, 30, 0, 0)

Python 3.6 添加了 %G, %V and %u directives :

>>> 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)

关于python - 找到 datetime.isocalendar() 的倒数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/304256/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com