简体   繁体   English

用一年中的年和周计算的Python日期不正确

[英]Python date calculating with year and week of year is incorrect

We are having an issue when calculating the start of the first week in 2019. 在计算2019年第一周的开始时遇到问题。

The parameters are year and week_of_year . 参数是yearweek_of_year We are always staring the week at Monday. 我们总是盯着星期一的一周。

The code to get the first day of a specific year: 获取特定年份第一天的代码:

from datetime import datetime

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

This works for most of the years, but not in the case when year = 2019 and week_of_year = 1 , Python computes this to the date 2019-01-02 and not the expected 2018-12-31 . 这适用于大多数年份,但不适用于year = 2019week_of_year = 1 ,Python将其计算为日期2019-01-02而不是预期的2018-12-31

Our current solution to solve this problem is: 我们当前解决此问题的解决方案是:

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)

Any other ideas on how to fix this issue? 关于如何解决此问题还有其他想法吗?

After consulting https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior , I can tell that %W does not respect ISO-definition of the week counter, but simply counts from the first monday in a year. 在咨询https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior之后 ,我可以知道%W不遵守星期计数器的ISO定义,而只是从一年中的第一个星期一。 The days before are put into week count 0... 前几天放入周计数0 ...

You can try %V together with %G : 您可以将%V%G一起尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM