Q:

Calculate the date 4 months from the current date using python programming

belongs to collection: Python Date and Time Exercises

0

Calculate the date 4 months from the current date

Given:

# 2020-02-25
given_date = datetime(2020, 2, 25).date()

Expected output:

2020-06-25

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Solution:

  • We need to use the Python dateutil module’s relativedelta. We can add 4 months into the given date using a relativedelta.
  • The relativedelta is useful when we want to deal months with day 29, 30 31, It will properly adjust the days.
from datetime import datetime

from dateutil.relativedelta import relativedelta

# 2020-02-25
given_date = datetime(2020, 2, 25).date()

months_to_add = 4
new_date = given_date + relativedelta(months=+ months_to_add)
print(new_date)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Calculate number of days between two given dates u... >>
<< Convert the following datetime into a string using...