Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get last day of a month in Python?
You can use the calendar module to find the weekday of first day of the month and number of days in month. Using this information you can easily get the last day of the month. The calendar module has a method, monthrange(year, month) that returns the weekday of first day of the month and number of days in month, for the specified year and month.
Using calendar.monthrange()
The monthrange() function returns a tuple containing the weekday of the first day and the total number of days in the month ?
import calendar
# Get weekday of first day and number of days in December 2017
first_day_weekday, num_days = calendar.monthrange(2017, 12)
print(f"First day weekday: {first_day_weekday}")
print(f"Number of days: {num_days}")
# Calculate the weekday of the last day
last_day_weekday = (first_day_weekday + num_days - 1) % 7
print(f"Last day weekday: {last_day_weekday}")
print("(0=Monday, 1=Tuesday, ..., 6=Sunday)")
First day weekday: 4 Number of days: 31 Last day weekday: 6 (0=Monday, 1=Tuesday, ..., 6=Sunday)
Getting the Actual Date
To get the complete date of the last day of the month ?
import calendar
from datetime import datetime
year, month = 2017, 12
# Get the number of days in the month
_, num_days = calendar.monthrange(year, month)
# Create the last day date
last_day_date = datetime(year, month, num_days)
print(f"Last day of {month}/{year}: {last_day_date.strftime('%Y-%m-%d (%A)')}")
Last day of 12/2017: 2017-12-31 (Sunday)
Alternative Method Using datetime
You can also find the last day by going to the first day of the next month and subtracting one day ?
from datetime import datetime, timedelta
def get_last_day_of_month(year, month):
if month == 12:
next_month = datetime(year + 1, 1, 1)
else:
next_month = datetime(year, month + 1, 1)
last_day = next_month - timedelta(days=1)
return last_day
# Example usage
last_day = get_last_day_of_month(2017, 12)
print(f"Last day: {last_day.strftime('%Y-%m-%d (%A)')}")
print(f"Weekday number: {last_day.weekday()}") # 0=Monday, 6=Sunday
Last day: 2017-12-31 (Sunday) Weekday number: 6
Comparison
| Method | Imports Needed | Best For |
|---|---|---|
calendar.monthrange() |
calendar |
Getting weekday and day count |
datetime + timedelta |
datetime |
Getting complete date object |
Conclusion
Use calendar.monthrange() to get the weekday of the last day, or combine datetime with timedelta to get the complete last day date. Both methods handle leap years automatically.
