ISO8601 week number of the year

 

 

import datetime

datetime.date(2023, 1, 1).isoweekday()


def leap_year(year: int) -> bool:
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0


for year in range(2001, 2101):
    weekday = datetime.date(year, 1, 1).isoweekday()
    n_days = 366 if leap_year(year) else 365
    weeks = 0
    if weekday <= 4:  # Monday Tuesday Wednesday Thursday
        weeks += 1
        # Monday -7(1) Tuesday -6(2) Wednesday -5(3)
        n_days = n_days - (8 - weekday)
    else:  # Friday Saturday Sunday
        # Friday -3(5) Saturday -2(6) Sunday -1(7)
        n_days = n_days - (8 - weekday)

    quotient, remainder = divmod(n_days, 7)
    
    if not remainder:
        weeks += quotient
    else:
        last_weekday = datetime.date(year, 12, 31).isoweekday()
        weeks += quotient
        if last_weekday >= 4:
            weeks += 1

    print(f'year: {year}, weeks: {weeks}')

 

posted @ 2024-02-10 20:31  ascertain  阅读(6)  评论(0编辑  收藏  举报