一年中的日历周数?

时间:2015-03-25 17:46:06

标签: python date

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

我在标准库中找不到函数。

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

  

例如,2004年开始于星期四,因此ISO 2004年的第一周从2003年12月29日星期一开始,到2004年1月4日星期日结束,因此date(2003, 12, 29).isocalendar() == (2004, 1, 1)date(2004, 1, 4).isocalendar() == (2004, 1, 7)

3 个答案:

答案 0 :(得分:6)

根据相同的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

  
      
  • 今年是最后一个星期四。
  •   
  • 这是最后一周,12月份的成员占多数(4个或更多)。
  •   
  • 它的中间日,星期四,在结束的一年。
  •   
  • 最后一天是最接近12月31日的星期日。
  •   
  • 它有12月28日。因此,最新的可能日期是12月28日至1月3日,即最早的12月21日至28日。
  •   

对于更全面的周计算,您可以使用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

答案 1 :(得分:3)

你几乎就在那里,取12月28日的日期。如果在那之后有一个星期一,它在旧年只有3天,因此是新年的第1周。

答案 2 :(得分:0)

我认为Martijn Pieters有一个很好的解决方案,唯一的缺点是您必须安装模块,如果您的唯一用例是在星期几,这是一个过大的选择,这是您无需安装任何模块就可以做的事情。 (仅供参考,已针对Python 3.8进行了测试)

#!/usr/bin/env python3.8
from datetime import timedelta,datetime

#change the your_year to the year you would like to get the last week#
your_year= 2020
# we add 1 to get to the next year !
next_year_date =datetime(your_year+1, 1, 1)
# we subtract 4 days only to go to the last day of previous/your_year 
# this is because of [ISO spec][1]  
last_day = next_year_date - timedelta(days=4)
print(last_day)
# we just get the week count
print(last_day.isocalendar()[1] )