How to get last day of month in Python?

Earlier we have see how to find the first day of the month, Now we will see how to find the last day of the month in Python. There is a method called monthrange in the calendar module. The monthrange method gets in the year and the month as input and returns the first day of the month and the number of days in a month. Using the monthrange method, we can easily get the last day of the moth. Let’s see how it works:

from datetime import datetime
from calendar import monthrange

def last_day_of_month(date_value):
    return date_value.replace(day = monthrange(date_value.year, date_value.month)[1])

given_date = datetime.today().date()
print("\nGiven date:", given_date, " --> Last day of month:", last_day_of_month(given_date))

given_date = datetime(year=2008, month=2, day=1).date()
print("\nGiven date:", given_date, " --> Last day of month:", last_day_of_month(given_date))

given_date = datetime(year=2009, month=2, day=1).date()
print("\nGiven date:", given_date, " --> Last day of month:", last_day_of_month(given_date), "\n")
Getting last day of month in Python

More Python Tips

Reference

  • More about calendar.monthrange() method at Python docs.


1 thought on “How to get last day of month in Python?”

  1. I want to add these values of first and last day of the month to a dictonary. After adding these values when I print the dictionary it shows last day as( ‘last day’: datetime.date(2020, 8, 31)). Any suggestions on how this can be fixed

    Reply

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.