Get last day of month in Python

Last day of month in Python

In this article, we will discuss how to find the last day of the month in Python using different modules.

Using the calendar.monthrange() function

The monthrange() function is used to return a tuple containing the first weekday of the month and the total number of days in the month. We have to pass the year and month to this function.

After getting the above mentioned values, we will create a new date object using the given date and use the replace() function to replace the day number with the total number of days in that month.

For example,

Output:

2021-05-31

For Python 3.7 and above, we can also use the monthlen() function from this module which returns the total number of days in a month.

Using the dateutil.relativedelta() function

The dateutil can be considered as an extension to the datetime module. Both these modules are very often used together and the dateutil module provides a vast range of functionalities to operate on datetime objects. We can use the relativedelta() function to compute the last date of the month from a given date.

For example,

Output:

2021-05-31

The above code gives the last date of the month in a datetime object.

Using the datetime module

We can create our own little function to return the last day of the month using the datetime module. This method can be considered unconventional but provides the desired result. Basically, we calculate the first day of the next month from a given date, then we subtract 1 day from this date and we get the date of the last day of the month.

The following code implements the above method.

Output:

2021-05-31

0 here indicates that the day is Monday.

Using the pandas.end_time() function

The pandas module deals very frequently with data containing dates and time values. That is why it is equipped with different functions that can work with such values. It is not advisable to use methods from this module unless one is working with DataFrames.

The end_time() function can return the final date and time of a given period. We can specify the date and set frequency to ‘M’, and we will get the final date of the month.

For example,

Output:

2021-05-31

Using the pandas.date_range()

The date_range() function is used to produce an object containing dates from the start to end of the specified values. We can modify this function to get the last day of the month.

See the following code.

Output:

2021-05-31 00:00:00

That’s all about how to get last day of month in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *