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(days=next_month.day) print(last_day) #29