问题描述
在Python中,我们如何找出一年中的日历周数?
In Python, how can we find out the number of calendar weeks in a year?
我在标准库中找不到函数。
I didn't find a function in the standard library.
然后我想到了 date(year,12,31).isocalendar()[1]
,但是
推荐答案
根据相同的ISO规范,每年1月4日总是 。通过相同的计算,每年的最后一周通常是12月28日。您可以使用它来查找给定年份的最后一周的数字:
According to the same ISO specification, January 4th is always going to be week 1 of a given year. By the same calculation, the 28th of December is then always in the last week of the year. You can use that to find the last week number of a given year:
from datetime import date, timedelta
def weeks_for_year(year):
last_week = date(year, 12, 28)
return last_week.isocalendar()[1]
另请参见Wikipedia,ISO周文章:
Also see Wikipedia, the ISO week article lists all properties of the last week:
要进行更全面的周计算,可以使用;它具有 Week.last_week_of_year()
类方法:
For more comprehensive week calculations, you could use the isoweek
module; it has a Week.last_week_of_year()
class method:
>>> import isoweek
>>> isoweek.Week.last_week_of_year(2014)
isoweek.Week(2014, 52)
>>> isoweek.Week.last_week_of_year(2014).week
52
这篇关于一年的日历周数是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!