[Python] How to Get the Last Day of a Specific Month

To determine how many days are in a specific month (28, 30, or 31) or to check for leap years in Python, the most reliable method is to use the monthrange() function from the standard calendar library.

This eliminates the need to implement your own logic for calculating leap years or remembering which months have 30 or 31 days.

目次

Implementation Example: Checking the Last Day of February

Here, we will implement code to check February 2025 to see what day of the week it starts on and how many days it has (i.e., identifying the last date).

Source Code

import calendar

# Target year and month
target_year = 2025
target_month = 2

# Execute calendar.monthrange(year, month)
# Returns a tuple: (weekday index of the 1st, number of days in month)
# Weekday index: 0=Monday, ... 6=Sunday
weekday_index, last_day = calendar.monthrange(target_year, target_month)

print(f"Target: {target_year}/{target_month}")
print("-" * 30)

# Output results
print(f"Weekday of 1st: {weekday_index} (0:Mon - 6:Sun)")
print(f"Days in month : {last_day} days")
print(f"Last day      : {target_year}/{target_month}/{last_day}")

Execution Result

Target: 2025/2
------------------------------
Weekday of 1st: 5 (0:Mon - 6:Sun)
Days in month : 28 days
Last day      : 2025/2/28

Explanation

calendar.monthrange(year, month)

This function calculates calendar information for the specified year and month and returns a tuple with two values:

  1. First Return Value (Weekday): An integer indicating the day of the week for the 1st of that month (0 is Monday, 6 is Sunday).
  2. Second Return Value (Number of Days): How many days are in that month (which equals the last date of the month).

Automatic Leap Year Detection

monthrange automatically determines if the specified year is a leap year.

For example, if you change target_year in the code above to 2024 (a leap year), the number of days will automatically return 29. This function is very useful for end-of-month processing and calculating payment deadlines.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次