How to find the dates of the last Sunday of each month of a given year in Python

1 Answer

0 votes
import sys
from datetime import date, timedelta

# Return all last Sundays of each month in a given year
def last_sundays_of_year(year):
    for month in range(1, 13):

        # Last day of the month
        d = date(year, month, 1)
        d = d.replace(day=28) + timedelta(days=4)   # jump to next month
        d = d.replace(day=1) - timedelta(days=1)    # last day of this month

        # Walk backward to Sunday
        while d.weekday() != 6:   # Sunday = 6
            d -= timedelta(days=1)

        yield d


def main():
    year = int(sys.argv[1]) if len(sys.argv) > 1 else 2026

    for d in last_sundays_of_year(year):
        print(d.strftime("%m/%d/%Y"))


if __name__ == "__main__":
    main()


"""
run:

01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026

"""

 



answered 10 hours ago by avibootz

Related questions

...