Python Add Months To Date Example
Chapter:
Python
Last Updated:
14-05-2023 05:56:55 UTC
Program:
/* ............... START ............... */
from datetime import date
from dateutil.relativedelta import relativedelta
# Get the current date
current_date = date.today()
print("Current date:", current_date)
# Add 3 months to the current date
future_date = current_date + relativedelta(months=3)
print("Date after adding 3 months:", future_date)
/* ............... END ............... */
Output
Current date: 2023-05-14
Date after adding 3 months: 2023-08-14
Please note that the actual output may vary depending on the current system date when you run the program.
Notes:
-
We start by importing the necessary modules: date from the datetime module and relativedelta from the dateutil.relativedelta module. The date module provides classes for working with dates, while relativedelta allows us to perform arithmetic operations on dates.
- We use the date.today() function to get the current date. This function returns a date object representing the current local date.
- Next, we add 3 months to the current date using the relativedelta(months=3) expression. The relativedelta class provides a way to calculate the difference between two dates with flexible options. Here, we create a relativedelta object and specify the number of months to add as months=3.
- Finally, we print the future date after adding 3 months using the print() function. This displays the updated date in the console.
- By using the relativedelta class, we can handle cases where adding a fixed number of months may result in varying lengths of months or accounting for leap years. It provides more flexibility compared to simply incrementing the month field of a date object.