Python Practice › Datetime Programs › Program 10
Add months to a date
Write a Python program to add months to a date, clamping to the month’s last day.
Input
2026-01-31 + 1 month
Output
2026-02-28 2027-02-15
Approach
- Calculate the new year and month, then limit the day.
Solution
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-7
Work in zero-based months so // and % handle the year change.
Line 8
31 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.