Write a Python program to add a month with a specified date


The program starts by importing the date and timedelta classes from the datetime module, and the calendar module from the Python Standard Library. A variable sd is created, which is a date object representing the date "October 18, 2022".

The calendar.monthrange function is called with the year and month of the sd date as arguments. This function returns a tuple with two values: the first day of the week of the first day of the month (where Monday is 0 and Sunday is 6), and the number of days in the month. The second value of the tuple is stored in the m variable, which represents the number of days in the month.

The expression sd + timedelta(days=m) creates a new date object by adding the number of days in the month (stored in m) to the sd date, using the timedelta class to represent the offset. Finally, the result of the expression is printed using the print function.

Source Code

from datetime import date, timedelta
import calendar
sd = date(2022, 10, 18)
m = calendar.monthrange(sd.year, sd.month)[1]
print(sd + timedelta(days=m))

Output

2022-11-18

Example Programs