How to Find the Last Day of the Month Using Python
- Find the Last Day of the Month Using the Calendar Library in Python
- Find the Last Day of the Month Using the DateTime Module in Python
- Find the Last Day of the Month Using the Arrow Library
- Find the Last Day of the Month Using the Pandas Module
- Conclusion
It can be challenging to remember the last day of every month and be certain about it. Have you ever considered that there should be a computer program that shows you the last day of any month of any year with a few lines of code?
This article will teach us how to create Python programs that easily let us find the last day of the month using standard Python libraries. We will use inbuilt libraries like calendar
and datetime
and some third-party libraries like pandas
and arrow
to find the last day of the month in Python.
Find the Last Day of the Month Using the Calendar Library in Python
In this section, we will use the inbuilt Python library calendar
to find the last day of the month.
This program uses the calendar
subfunction monthrange
, which takes in two parameter arguments, year
and month
, and returns a key-pair value of (week_day_of_first_day, number_of_days)
.
The first value indicates the first weekday of the month (0 is Monday, and 6 is Sunday), while the second value shows the last day of the month.
import calendar
last_day = calendar.monthrange(2000, 1)
print(last_day)
January has 31 days, and in the year 2000, the first day was on a Saturday.
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
(5, 31)
Process finished with exit code 0
Let’s check the program by giving some leap years as input to see if it correctly finds the last day of the month in Python.
import calendar
last_day1 = calendar.monthrange(2000, 2)
print(last_day1)
last_day2 = calendar.monthrange(2004, 2)
print(last_day2)
The leap years will be displayed accordingly.
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
(1, 29)
(6, 29)
Process finished with exit code 0
Find the Last Day of the Month Using the DateTime Module in Python
The datetime
library is also an inbuilt library used to find the last day of the month in Python.
Subtract a Day From Every Month’s First Day to Find the Last Day of the Month
This program finds the last day of the month when the month and year are provided as input.
import datetime
year = 2001
month = 2
v = datetime.date(year + int(month / 12), (month % 12) + 1, 1) - datetime.timedelta(
days=1
)
print(v)
Let’s break down the code:
The first line imports the datetime
library. Two variables, year
and month
, are created that take input for the year and the month. The subfunction datetime.date()
takes three values inside the parameter as the date.
This program uses the logic that going back a day from the first day of the month takes us to the last day of the previous month. This gives us the last day of all months except December, which brings us to the last day of the previous year.
The program adds a 1
to the year for December to combat this issue using the line:
datetime.date(year + int(month / 12))
Similarly, for the month, if it is December, the program adds a 1
to the modulus of month % 12
.
This sets the month to 1
, which has the same number of days as 12
without changing the current year. Lastly, a day is subtracted from the current date using the datetime.timedelta(days=1)
function.
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2001-02-28
Process finished with exit code 0
Another way of doing this using the datetime
library is to create a method and return two values from it, one for December and the other for the rest of the months. Let’s check the program below.
import datetime
def last_day_of_month(date):
if date.month == 12:
return date.replace(day=31)
return date.replace(month=date.month + 1, day=1) - datetime.timedelta(days=1)
print(last_day_of_month(datetime.date(2022, 10, 25)))
A method last_day_of_month
is created with a parameter date
. Inside the if
statement, it is checked if the month is December using date.month == 12
.
If the condition is true, the day is replaced by date.replace(day=31)
. Otherwise, the date
is replaced with the first day and the next month by incrementing month=date.month + 1
, then a day is subtracted from it, bringing the date to the last date of the given month.
An example is given below:
return date.replace(month=date.month + 1, day=1) - datetime.timedelta(days=1)
Lastly, the method is called by passing a date datetime.date()
, and then it is printed. It offers a more straightforward solution than the previous example.
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2022-10-31
Process finished with exit code 0
Use Preloaded Dates Stored in an Array Using a for
Loop to Find the Last Day of the Month
Another instance of using the datetime
library is to create an array of the month’s last days, run it in a loop, and let the datetime
library filter out the invalid dates.
See the example code below.
from datetime import datetime
def find_last_day(year, month):
end_days = [31, 30, 29, 28, 27]
for i in end_days:
try:
date = datetime(year, month, i)
except ValueError:
continue
else:
return date.date()
return None
print(find_last_day(2020, 2))
The program uses a method find_last_day()
with two parameters, year
and month
. In an array end_days
, the last few possible days are stored.
A for
loop is created that runs for the number of elements in end_days
. Inside a try
block, a variable stores the date using the datetime()
subfunction.
The value of month and year is set as per parameter, and in the day value, i
is stored.
Inside the except
block, a condition for ValueError
is given, which discards the i
value in the variable date
for an invalid month value. Then the loop is rerun using continue
.
The method returns the date
inside an else
block if a valid value is found. Lastly, return None
is used so that the method does not return any other value.
The program searches for the appropriate value of day
from the given array. For December, the loop finds 31 and returns the value; for months like November, only 30 is possible, so it returns that day.
Similarly, February 31 and 30 cannot be possible, so the loop runs over them. If the year given is a leap year, 29 is returned by the loop; else, 28 is returned.
Lastly, the method is called by passing the month of February and the year 2020.
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2020-02-29
Process finished with exit code 0
As we can see, February 2020 was a leap year.
Print the Last Day of All Months of a Calendar Year to Find the Last Day of the Month
The library datetime
can also be used to find the last day of all the months in Python in a calendar year and print them all. Let’s look at the program.
import datetime
def month_end(date):
next_month = date.replace(day=28) + datetime.timedelta(days=4)
return next_month - datetime.timedelta(days=next_month.day)
for month in range(1, 13):
print(month_end(datetime.date(2022, month, 1)))
Let’s break down the code:
A method month_end
is created that takes a parameter date
. Inside this method, a variable next_month
takes the date
and replaces the day with 28
using date.replace(day=28)
as every month has 28 days minimum.
After the value is replaced, 4 days are added to this value to shift the date
to next month’s first or second day, depending on the number of days in the previous month.
Suppose the current date is 2000, 3, 4
, and the day’s value for this month is 4
. Subtracting this day value from the date
will take it to the last day of the previous month - 2000, 2, 28
; this logic is used here in this program.
The day in the variable next_month
is subtracted from itself and returned from the method using the syntax:
return next_month - datetime.timedelta(days=next_month.day)
We have created a for
loop that uses the instance month
to run a loop in a range of (1,13)
. Inside the loop, the method month_end
is called by passing datetime.date
, providing the method with the year and day.
The month is replaced by the instance month
used inside the for
loop to pass 12 months to the method.
for month in range(1, 13):
print(month_end(datetime.date(2022, month, 1)))
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2022-01-31
2022-02-28
2022-03-31
2022-04-30
2022-05-31
2022-06-30
2022-07-31
2022-08-31
2022-09-30
2022-10-31
2022-11-30
2022-12-31
Process finished with exit code 0
Shown in the output are all the last days of a calendar year.
Find the Last Day of the Month Using the Arrow Library
This is a third-party Python library that can be used for date manipulation. It will be used to find the last day of the month in Python.
The program uses the Arrow subfunction utcnow()
to get the current universal time. It finds the ceiling of the month using ceil('month').date
.
import arrow
print(arrow.utcnow().ceil("month").date())
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2022-10-31
Process finished with exit code 0
The code gives the last date of the current month.
Find the Last Day of the Month Using the Pandas Module
This section uses a third-party Python library, Pandas, to find the month’s last day. Here, the program imports two library packages - datetime
and pandas
.
A method check_month_end
is created that takes in a parameter date
. This method takes the parameter date
and adds the remaining days of that month using date + pd.offsets.MonthEnd(0)
.
Below is the example code:
from datetime import datetime
import pandas as pd
def check_month_end(date):
return date + pd.offsets.MonthEnd(0)
print(check_month_end(datetime(2005, 2, 6)))
print(check_month_end(datetime(2004, 2, 29)))
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
2005-02-28 00:00:00
2004-02-29 00:00:00
Process finished with exit code 0
The output is in a Pandas timestamp format and displays the last day of the month.
Check if a Day Is the Last Day of the Month Using Pandas
Pandas can be used to check if a given date is the last day of the month. Unlike the few previous programs, this one takes user input and checks if the given day is valid or not.
The program uses the parameter value to check if it matches the end of the month using date + pd.offsets.MonthEnd(0) == date
. The method returns Boolean values when it is called.
See the example code provided.
from datetime import datetime
import pandas as pd
def check_month_end(date):
return date + pd.offsets.MonthEnd(0) == date
print(check_month_end(datetime(1996, 5, 16)))
print(check_month_end(datetime(1996, 5, 31)))
Output:
"C:\Users\Win 10\venv\Scripts\python.exe" "C:/Users/Win 10/main.py"
False
True
Process finished with exit code 0
Conclusion
In this article, we’ve learned the various ways to find the last day of the month in Python using inbuilt libraries like datetime
and calendar
as well as third-party libraries like arrow
and pandas
.