In this Python lesson, you’ll learn how to find the last day (last date) of a month from a given date. Also, we will cover how to get the last day of next month and the previous month.
Also, see Python Get First Day Of Month.
Table of contents
How To Find The Last Day Of The Month In Python
Sometimes we need to find the last day of a month from a given date. For example, let’s assume you have a dateTime ‘2022-8-12’ and you want to write a code that will return you 2022-8-31, i.e., the last day of the month or the last date of a month.
The below steps show how to use the calendar module to find the last day of a month in Python.
- Import datetime class from a datetime module
Python datetime module provides various functions to create and manipulate the date and time. Use the
from datetime import datetime
statement to import adatetime
class from a datetime module. - Import calendar module
This module allows you to output calendars like the Unix cal program and provides additional useful functions related to the calendar. Use the
import calendar
command to add the calendar module to your script. - Store datetime object in a variable
Store the original datetime object in a variable for further processing. Or you can use the
datetime.today()
to get the current datetime if you want to find the last date of a current month. - Use the monthrange() method
The
calendar.monthrange()
function returns the weekday of the first day of the month and the number of days in a month, for the specified year and month. In short, it returns a result in tuple format weekday (0-6 ~ Mon-Sun) and number of days (28-31) for provided year and month
For example,calendar.monthrange(2022, 9)
will return(3, 30)
. i.e., the last day is 30.
Example: Get The Last Day Of The Month
# Get the last day of the month from a given date
import calendar
from datetime import datetime
input_dt = datetime(2022, 9, 13)
print("The original date is:", input_dt.date())
# monthrange() to gets the date range
# year = 2022, month = 9
res = calendar.monthrange(input_dt.year, input_dt.month)
day = res[1]
print(f"Last date of month is: {input_dt.year}-{input_dt.month}-{day}")
# note:
# res [0] = weekday of first day (between 0-6 ~ Mon-Sun))
# res [1] = last day of the month
Output:
The original date is: 2022-09-13 Last date of month is: 2022-9-30
Get The Last Day Of The Month Using replace() and timedelta()
If you don’t want to import the calendar module just for this use case, you can use the combination of replace()
and timedelta()
method of a datetime module.
datetime.replace()
: This method replaces the DateTime object’s contents with the given parameters. This method has various parameters, but here we will use theday
parameter because we want to replace the day number of a datetime object with the last day of the month.timedelta()
: A timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution. We can use the timedelta to add or subtract weeks, days, hours, minutes, seconds, microseconds, and milliseconds from a given DateTime.
Now, let’s see the steps to achieve the same.
- First, import the datetime and timedelta class from a datetime module.
- Next, use the
day
parameter of a timedelta class to replace the date’s day number with 28 (each month contains at least 28 days). - Next, use the timedelta class to add four days to the new date. By doing this, you will get the next month.
- Now, subtract the number of the current day from the new date to get the last day of a month. (It brings us back to the original month).
Example: Get The Last Day Of The Month Using replace() and timedelta()
from datetime import datetime, timedelta
input_dt = datetime(2022, 9, 13)
print("The original date is:", input_dt.date())
next_month = input_dt.replace(day=28) + timedelta(days=4)
res = next_month - timedelta(days=next_month.day)
print(f"Last date of month is:", res.date())
Output:
The original date is: 2022-09-13 Last date of month is: 2022-09-30
Also, see Python Get First Day Of Month.
Get The Last Day Of The Month Using dateutil
Also, we can use the third-party library dateutil to get the last day of a month.
- Use
pip Install python-dateutil
to install it. - Next, just add 31 days to your date using the
dateutil.relativedelta(day=31)
to get the last day of the month.
Example:
from datetime import datetime
from dateutil.relativedelta import relativedelta
input_dt = datetime(2202, 9, 13)
print("The original date is:", input_dt.date())
# add 31 days to the input datetime
res = input_dt + relativedelta(day=31)
print(f"Last date of month is:", res.date())
Output:
The original date is: 2202-09-13 Last date of month is: 2202-09-30
Get Last Day of a Previous Month
- Import the datetime and timedelta class from a datetime module
- First, calculate the first day of a month using
res = input_dt.replace(day=1)
. - Now, use the timedelta class to subtract one day from the resultant date to get the last day of the previous month.
Example:
from datetime import datetime, timedelta
input_dt = datetime(2022, 9, 13)
first = input_dt.replace(day=1)
print('first day of a month:', first.date())
res = first - timedelta(days=1)
print('Last day of a previous month is:', res.date())
Output:
first day of a month: 2022-09-01 Last day of a previous month is: 2022-08-31
Get Last Day of a Next Month
- Import the datetime and timedelta class from a datetime module
- Next, use the day parameter of a timedelta class to replace the date’s day number with the 28 (because each month contains at least 28 days) to move to the next month
- Next, use the timedelta class to add four days to the new date. By doing this, you will get the next month.
- Repeat the 2 and 3 steps to get the second next month.
- Now, use the timedelta class to subtract one day from the resultant date to get the last day of the next month.
Example:
from datetime import datetime, timedelta
input_dt = datetime(2022, 9, 13)
print('Input date:', input_dt.date())
# move to first next month
next_month = input_dt.replace(day=28) + timedelta(days=4)
# Now move to the second next month
next_month = next_month.replace(day=28) + timedelta(days=4)
# come back to the first next month's last day
res = next_month - timedelta(days=next_month.day)
print('Last day of the next month:', res.date())
Output:
Input date: 2022-09-13 Last day of the next month: 2022-10-31
Leave a Reply