gpt4 book ai didi

python - 一年中的日历周数?

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:31 25 4
gpt4 key购买 nike

在 Python 中,我们如何找出一年中的日历周数?

我没有在标准库中找到函数。

然后我想到了 date(year, 12, 31).isocalendar()[1],但是

For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that date(2003, 12, 29).isocalendar() == (2004, 1, 1) and date(2004, 1, 4).isocalendar() == (2004, 1, 7).

最佳答案

根据相同的 ISO 规范,1 月 4 日总是将成为给定年份的第 1 周。通过同样的计算,12 月 28 日总是在一年的最后一周。您可以使用它来查找给定年份的最后一周数:

from datetime import date, timedelta

def weeks_for_year(year):
last_week = date(year, 12, 28)
return last_week.isocalendar()[1]

另请参阅维基百科、ISO 周文章 lists all properties of the last week :

  • It has the year's last Thursday in it.
  • It is the last week with a majority (4 or more) of its days in December.
  • Its middle day, Thursday, falls in the ending year.
  • Its last day is the Sunday nearest to 31 December.
  • It has 28 December in it. Hence the latest possible dates are 28 December through 3 January, the earliest 21 through 28 December.

要进行更全面的周计算,您可以使用 isoweek module ;它有一个 Week.last_week_of_year() 类方法:

>>> import isoweek
>>> isoweek.Week.last_week_of_year(2014)
isoweek.Week(2014, 52)
>>> isoweek.Week.last_week_of_year(2014).week
52

关于python - 一年中的日历周数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com