Add months to a date
MediumDatetime Programs · 10 of 20
Write a Python program to add months to a date, clamping to the month’s last day.
Input2026-01-31 + 1 month
Output2026-02-28 2027-02-15
Approach
- Calculate the new year and month, then limit the day.
Solution
Python
import calendarfrom datetime import date def add_months(d, months): month_index = d.month - 1 + months year = d.year + month_index // 12 month = month_index % 12 + 1 day = min(d.day, calendar.monthrange(year, month)[1]) return date(year, month, day) print(add_months(date(2026, 1, 31), 1), add_months(date(2026, 11, 15), 3))
Output
2026-02-28 2027-02-15
Line by line
Lines 5-7Work in zero-based months so // and % handle the year change.
Line 831 January plus one month becomes 28 February, because February has no 31st.
Learn the concept
New to this topic? Read the lesson, then come back.
More datetime programs
← All 20 Datetime Programs