Home > Software design >  How do I calculate the date Three months from a input date using python
How do I calculate the date Three months from a input date using python

Time:02-24

I am using the datetime Python module. I am looking to calculate the date 3 months from the input date. Can you help me to get out of this issue.Thanks in advance

import datetime
today = "2022-02-24"

three = today   datetime.timedelta(30*3)
print (three)

Also I tried using "relativedelta"

CodePudding user response:

You can't add a timedelta to a string, you need to add it to a datetime instance

Note that 90 days, isn't really 3 months

from datetime import datetime, timedelta

today = "2022-02-24"
three = datetime.strptime(today, "%Y-%m-%d")   timedelta(30 * 3)
print(three)  # 2022-05-25 00:00:00

three = datetime.today()   timedelta(30 * 3)
print(three)  # 2022-05-24 21:32:35.048700

CodePudding user response:

With relativedelta of dateutil package, you can use:

from dateutil.relativedelta import relativedelta
from datetime import date

three = date.today()   relativedelta(months=3)

Output:

>>> three
datetime.date(2022, 5, 23)
  • Related