To get the last day of the month using Python, the easiest way is with the timerange() function from the calendar module to get the number of days in the month, and then create a new date.

import calendar
import datetime

currentDate = datetime.date.today()
lastDayOfMonth = datetime.date(currentDate.year, currentDate.month, calendar.monthrange(currentDate.year, currentDate.month)[1])

print(currentDate)
print(lastDayOfMonth)

#Output:
2022-03-06
2022-03-31

When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display a particular day.

We can easily get the last day of a month with the help of the monthrange function from the calendar module.

The monthrange() function takes in a year and month, and returns the weekday of first day of the month and number of days in month.

We can pass a year and month to monthrange() and then get the number of days of the month accessing the second element of the returned tuple.

After accessing the second element of the returned tuple, we create a new date using datetime.date().

Below is a simple example in Python of how to get last day of a month.

import calendar
import datetime

currentDate = datetime.date.today()
lastDayOfMonth = datetime.date(currentDate.year, currentDate.month, calendar.monthrange(currentDate.year, currentDate.month)[1])

print(currentDate)
print(lastDayOfMonth)

#Output:
2022-03-06
2022-03-31

How to Get the First Day of the Month Using Python

If you instead want to get the first day of a month in Python, you can easily use the datetime module to do so.

Getting the first day of a given month is very easy with Python.

To get the first day of a month, we just need to pass ‘1’ in the third argument of the date() function.

Below is how to create a date with the first day of the month in Python.

import datetime

currentDate = datetime.date.today()
lastDayOfMonth = datetime.date(currentDate.year, currentDate.month, 1)

print(currentDate)
print(lastDayOfMonth)

#Output:
2022-03-06
2022-03-01

Hopefully this article has been useful for you to learn how to get the last day of a month using Python.

Categorized in:

Python,

Last Update: February 26, 2024