# Time 5, Exercise 3: ISO week dates, long and short years from datetime import date, timedelta def iso_week_own(d): """ISO week number and year, using the rule: week 1 is the week containing the year's first Thursday.""" # Move to the Thursday of the same Monday-to-Sunday week thursday = d + timedelta(days=3 - d.weekday()) iso_year = thursday.year jan1 = date(iso_year, 1, 1) week = (thursday - jan1).days // 7 + 1 return iso_year, week # 1. Compare with Python's own isocalendar for every day from 1900 to 2100 bad = 0 d = date(1900, 1, 1) while d <= date(2100, 12, 31): if iso_week_own(d) != tuple(d.isocalendar())[:2]: bad += 1 d += timedelta(days=1) print("disagreements with isocalendar:", bad) # 2. Today, as a week date today = date(2026, 11, 9) y, w, wd = today.isocalendar() print("2026-11-09 is", str(y) + "-W" + str(w) + "-" + str(wd)) # 3. Which years have 53 weeks? Dec 28 is always in the last ISO week of its year. long_years = [yr for yr in range(2015, 2041) if date(yr, 12, 28).isocalendar()[1] == 53] print("53-week years 2015-2040:", long_years) # 4. Across a full 400-year Gregorian cycle print("days in 400 years:", 400 * 365 + 97, "= weeks:", (400 * 365 + 97) / 7) count = sum(1 for yr in range(2001, 2401) if date(yr, 12, 28).isocalendar()[1] == 53) print("53-week years in 400:", count) # 5. A year-boundary surprise print("2027-01-01 is ISO", date(2027, 1, 1).isocalendar()[:2]) # Output when run: # disagreements with isocalendar: 0 # 2026-11-09 is 2026-W46-1 # 53-week years 2015-2040: [2015, 2020, 2026, 2032, 2037] # days in 400 years: 146097 = weeks: 20871.0 # 53-week years in 400: 71 # 2027-01-01 is ISO (2026, 53) # Reading the output: 146097 divides exactly by 7, so the Gregorian calendar, weekdays # included, repeats every 400 years. 71 of those 400 years have 53 ISO weeks, and # 52 x 400 + 71 = 20871 weeks, which matches. Early January days can belong to the # last week of the previous year, as 1 January 2027 does.