Get First & Last Day of Month in Python (Example)
In this tutorial, you’ll learn how to get the first and last day of a month using the Python programming language.
The structure of the tutorial is shown below:
Let’s dive into it!
import calendar from datetime import datetime from dateutil.relativedelta import relativedelta
Example 1: Using the Calendar Module
The calendar module provides the monthrange() function which takes a year and a month parameter, then returns the first day as an integer, and the total days in the month.
first_day, day_count = calendar.monthrange(2022,11) print(first_day, day_count) # 1 30
We can get the corresponding name of the first day by using the following method.
print(calendar.day_name[first_day]) # Tuesday
To get the day number and name of the last day of the month, we will do some addition in mod 7, since a week has 7 days. We need to add the first_day and the day_count and finally subtract 1 because day_count includes the first day of the month as well.
print(calendar.day_name[(first_day+day_count-1)%7]) # Wednesday
Example 2: Using datetime & relativedelta Objects
If you decide not to use the calendar module, you can utilize datetime and relativedelta objects. First, let’s set a sample date as shown below.
Note: A date object could have been used for this method as well.
sample_date = datetime(2022, 2, 14)
Next, we will only change the day field of the datetime object to be the first and last day of the month.
first_day = sample_date + relativedelta(day=1) last_day = sample_date + relativedelta(day=31)
Even if the month of the datetime object does not have 31 days in it, the modification sets the day to the last day of the month. Therefore, we get the following output:
print(first_day, last_day, sep='\n') # 2022-02-01 00:00:00 # 2022-02-28 00:00:00
Fun fact: Instead of the + operator, we can also use – operator and it yields the same output. This makes sense because this is actually not an addition operation, but an alteration of a specific field.
first_day_sub = sample_date - relativedelta(day=1) last_day_sub = sample_date - relativedelta(day=31) print(first_day_sub, last_day_sub, sep='\n') # 2022-02-01 00:00:00 # 2022-02-28 00:00:00
Afterwards, we can get the entire output with the ctime() function as shown below, this is basically the format of time display used on the corner of your PC.
print(first_day.ctime(), last_day.ctime(), sep='\n') # Tue Feb 1 00:00:00 2022 # Mon Feb 28 00:00:00 2022
However, if we need to get the date and name of the days separately, we can use the isformat() and strftime() functions. strftime() should be used with the %A parameter like
strftime('%A') to get the name of the day only.
print(first_day, first_day.strftime('%A')) print(last_day.isoformat(sep = ' '), last_day.strftime('%A')) # 2022-02-01 00:00:00 Tuesday # 2022-02-28 00:00:00 Monday
Video, Further Resources & Summary
Do you need more explanations on how to get the first and last day of a month? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could have a look at some other tutorials on Statistics Globe:
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Count Working Days Between Two Dates Excluding Weekends in Python
- Calculate Time Difference Between Two Columns of pandas DataFrame in Python
- Calculate Number of Hours, Minutes & Seconds Between Two datetimes in Python
- Calculate Number of Years, Months & Days Between Two Dates in Python
- Calculate Time Difference Between Two datetime Objects in Python
- Calculate Time Difference in Milliseconds Between Two datetimes
- How to Add & Subtract Weeks to & from Date in Python
- Add Days, Months & Years to datetime Object
- Introduction to Python
This post has shown how to get the first and last day of a month. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ömer Ekiz. You may have a look at Ömer’s author page to read more about his academic background and the other articles he has written for Statistics Globe.