【发布时间】:2018-10-16 20:02:27
【问题描述】:
我们在计算 2019 年第一周的开始时遇到了问题。
参数为year和week_of_year。我们总是在星期一盯着一周。
获取特定年份第一天的代码:
from datetime import datetime
result = datetime.strptime('%04d-%02d-1' % (year, week_of_year), '%Y-%W-%w').date()
这在大多数年份都有效,但在 year = 2019 和 week_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