Get the Last Day of a Month in Python

There are a few ways to get the last day of the month in Python. One way is to use the datetime module. The other way is to use the calendar module.

The calendar module has a function called monthrange() which returns the number of days in a given month. We can use this function to retrieve the last day of the month.

import calendar

month_range = calendar.monthrange(2022, 1)
print(month_range) # (5, 31)
month_range = calendar.monthrange(2022, 2)
print(month_range) # (1, 28)
month_range = calendar.monthrange(2022, 5)
print(month_range) # (6, 31)
month_range = calendar.monthrange(2022, 8)
print(month_range) # (0, 31)

last_day = month_range[1]

If you don’t want to import the calendar library, you can also use the following expression to get the last day of the month:

import datetime

source_date = datetime.datetime(2020, 2, 12)
next_month = source_date.replace(day=15) + datetime.timedelta(days=17)
last_day = next_month - datetime.timedelta(
print(last_day) #29

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.