Python - Get the last day of the month

By xngo on August 1, 2019

In Python, there are multiple ways to get the last day of the month. Here are some examples.

Use calendar module

The easiest way is to use the standard calendar module. It does have a method called monthrange(year, month) that will return 2 values: the weekday of the first day of the month and the number of days in the month. Use the number of days in the month to get the last day of the month. Here is how to get it.

import calendar
last_day_of_month = calendar.monthrange(2019,8)[1]
print(last_day_of_month)    # Output = 31

Calculate yourself

If you don't want to import the standard calendar module, you can calculate it yourself. Simply get a date for the next month and then subtract all days that are over since the beginning of the month. So, if your next month date fall on the 3rd of the month, then subtract 3 days. You will get the last day of the previous month. Here is the code using this principle.

import datetime 
any_date = datetime.datetime(2019, 8, 23)
 
# Guaranteed to get the next month. Force any_date to 28th and then add 4 days.
next_month = any_date.replace(day=28) + datetime.timedelta(days=4)
 
# Subtract all days that are over since the start of the month.
last_day_of_month = next_month - datetime.timedelta(days=next_month.day)
 
print(last_day_of_month.day)    # Output = 31

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.