Python - monthdatescalendar()


Python tip:

To get a list of weeks in a certain month, you can use the monthdatescalendar method.

You need to provide the date and month as arguments.

A list of lists, each containing 7 datetime.date objects is returned.

import calendar

cal = calendar.Calendar()
weeks = cal.monthdatescalendar(2022, 2)

print(weeks)

"""
Results:

[
    [
        datetime.date(2022, 1, 31),
        datetime.date(2022, 2, 1),
        datetime.date(2022, 2, 2),
        datetime.date(2022, 2, 3),
        datetime.date(2022, 2, 4),
        datetime.date(2022, 2, 5),
        datetime.date(2022, 2, 6),
    ],
    [
        datetime.date(2022, 2, 7),
        datetime.date(2022, 2, 8),
        datetime.date(2022, 2, 9),
        datetime.date(2022, 2, 10),
        datetime.date(2022, 2, 11),
        datetime.date(2022, 2, 12),
        datetime.date(2022, 2, 13),
    ],
    [
        datetime.date(2022, 2, 14),
        datetime.date(2022, 2, 15),
        datetime.date(2022, 2, 16),
        datetime.date(2022, 2, 17),
        datetime.date(2022, 2, 18),
        datetime.date(2022, 2, 19),
        datetime.date(2022, 2, 20),
    ],
    [
        datetime.date(2022, 2, 21),
        datetime.date(2022, 2, 22),
        datetime.date(2022, 2, 23),
        datetime.date(2022, 2, 24),
        datetime.date(2022, 2, 25),
        datetime.date(2022, 2, 26),
        datetime.date(2022, 2, 27),
    ],
    [
        datetime.date(2022, 2, 28),
        datetime.date(2022, 3, 1),
        datetime.date(2022, 3, 2),
        datetime.date(2022, 3, 3),
        datetime.date(2022, 3, 4),
        datetime.date(2022, 3, 5),
        datetime.date(2022, 3, 6),
    ],
]
"""