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)
anddate(2004, 1, 4).isocalendar() == (2004, 1, 7)
.
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]
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With