从Python中的ISO周数中获取日期

2024-04-29 04:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
What’s the best way to find the inverse of datetime.isocalendar()?

我有一个ISO8601年和周编号,我需要将其转换为该周(星期一)的第一天的日期。我该怎么做?

datetime.strptime()同时接受%W%U指令,但两者都不遵守datetime.isocalendar()使用的ISO 8601工作日规则。

更新:Python 3.6支持libc中也存在的%G%V%u指令,允许这一行:

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

Tags: ofthetodatetime指令findwhatway
2条回答

使用isoweek module可以使用:

from isoweek import Week
d = Week(2011, 40).monday()

%W将第一个星期一设为第1周,但ISO将第1周定义为包含1月4日。所以结果来自

datetime.strptime('2011221', '%Y%W%w')

在1月1日星期一和1月4日是不同的一周。 如果1月4日是星期五、星期六或星期日,则属于后者。 因此,以下方法应该有效:

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

相关问题 更多 >