Tim
Tim

Reputation: 99408

The number of calendar weeks in a year?

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.

I then thought about date(year, 12, 31).isocalendar()[1], but

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).

Upvotes: 9

Views: 11095

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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

def weeks_for_year(year):
    last_week = date(year, 12, 28)
    return last_week.isocalendar().week

Also see Wikipedia, the ISO week article 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.

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

Upvotes: 28

grepit
grepit

Reputation: 22382

I think Martijn Pieters has a great solution, the only draw back is you have to install the module which is an overkill if your ONLY use case is getting the week#, here is something you can do without installing any modules. (FYI this was tested for 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] )

Upvotes: 0

Ulrich Schwarz
Ulrich Schwarz

Reputation: 7727

You're almost there, take the date of Dec. 28. If there is a monday after that, it will only have 3 days in the old year and hence be week 1 of the new year.

Upvotes: 3

Related Questions