【问题标题】:Python date calculating with year and week of year is incorrect用年份和年份计算的 Python 日期不正确
【发布时间】:2018-10-16 20:02:27
【问题描述】:

我们在计算 2019 年第一周的开始时遇到了问题。

参数为yearweek_of_year。我们总是在星期一盯着一周。

获取特定年份第一天的代码:

from datetime import datetime

result = datetime.strptime('%04d-%02d-1' % (year, week_of_year), '%Y-%W-%w').date()

这在大多数年份都有效,但在 year = 2019week_of_year = 1 的情况下无效,Python 将其计算到日期 2019-01-02 而不是预期的 2018-12-31

我们目前解决这个问题的方法是:

from datetime import datetime, timedelta

result = datetime.strptime('%04d-%02d-1' % (year, week_of_year), '%Y-%W-%w').date()

# Fixes issue with Python date computing returning the incorrect date
# This only occures for some years. E.g. 2019.
offset = result.isocalendar()[1] - datetime.strptime('%04d-01-01' % year, '%Y-%m-%d').date().isocalendar()[1]
if offset > 0:
    result = result - timedelta(days=7)

关于如何解决此问题的任何其他想法?

【问题讨论】:

  • 第一周的第一天从 12 月开始,您的规则是什么?例如。 (2016, 1) 给出Jan 4th 而不是Dec 28th,即为什么Dec 31st 而不是Jan 7th 正确(注意:我得到Jan 7th 而不是Jan 2nd)。
  • @AChampion 嗯。当从 2019-01-07 获取周数时,它说 2 而不是 1。查看我的 Mac 日历,它还说日期 2018-12-31 在 2019 年的第 1 周:P
  • 您使用的是什么版本的 Python,我使用的是 3.7(和 Mac),并从 2019-01-07 == 1 获取周数。 datetime(2019, 1, 7).strftime('%W') # '01'(毫不奇怪,我得到了53 的周数2018/12/31)。
  • Python 默认使用基于0 的周数,您将混合使用python 的基于0 的周数和基于iso 的1 数。我认为您只需在您的strptime() 电话中将您的周数设置为0。它将在 isocalendar 中为您提供一周 1
  • 不幸的是,我认为它比这更复杂......isocalendar() 比我最初想象的更复杂。它基于完整的 52 或 53 周年,因此第 1 周不会简单地映射到 python 中的第 0 周,例如datetime(2016, 1, 1).isocalendar() # (2015, 53, 5)datetime(2013, 12, 31).isocalendar() # (2014, 1, 2)。顺便说一句,Calendar.app 只是一个基于 1 的日历周,相当于 Python 中基于 0 的周。你真的需要isocalendar()吗?

标签: python date week-number


【解决方案1】:

在咨询https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior 之后,我可以看出%W 不尊重周计数器的 ISO 定义,而只是从一年中的第一个星期一开始计算。前几天被放入周数 0...

你可以试试%V%G:

result = datetime.strptime('%04d-%02d-1' % (year, 1), '%G-%V-%w').date()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2011-02-26
    • 1970-01-01
    相关资源
    最近更新 更多