找到 datetime.isocalendar() 倒数的最佳方法是什么? [英] What's the best way to find the inverse of datetime.isocalendar()?

查看:35
本文介绍了找到 datetime.isocalendar() 倒数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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%u 指令:

<预><代码>>>>datetime.strptime('2011 22 1', '%G %V %u')datetime.datetime(2011, 5, 30, 0, 0)

原答案

我最近不得不自己解决这个问题,并想出了这个解决方案:

导入日期时间def iso_year_start(iso_year):给定 ISO 年第一天的公历日期"第四_jan = datetime.date(iso_year, 1, 4)delta = datetime.timedelta(fourth_jan.isoweekday()-1)返回fourth_jan - deltadef iso_to_gregorian(iso_year, iso_week, iso_day):给定 ISO 年、周和日的公历日期"year_start = iso_year_start(iso_year)返回 year_start + datetime.timedelta(days=iso_day-1,weeks=iso_week-1)

一些测试用例:

<预><代码>>>>iso = datetime.date(2005, 1, 1).isocalendar()>>>异(2004, 53, 6)>>>iso_to_gregorian(*iso)datetime.date(2005, 1, 1)>>>iso = datetime.date(2010, 1, 4).isocalendar()>>>异(2010, 1, 1)>>>iso_to_gregorian(*iso)datetime.date(2010, 1, 4)>>>iso = datetime.date(2010, 1, 3).isocalendar()>>>异(2009, 53, 7)>>>iso_to_gregorian(*iso)datetime.date(2010, 1, 3)

The Python datetime.isocalendar() method returns a tuple (ISO_year, ISO_week_number, ISO_weekday) for the given datetime object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?

解决方案

Python 3.8 added the fromisocalendar() method:

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

Python 3.6 added the %G, %V and %u directives:

>>> datetime.strptime('2011 22 1', '%G %V %u')
datetime.datetime(2011, 5, 30, 0, 0)

Original answer

I recently had to solve this problem myself, and came up with this solution:

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)

A few test cases:

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

这篇关于找到 datetime.isocalendar() 倒数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆