0

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"

azro
  • 53,056
  • 7
  • 34
  • 70
Treesa
  • 29
  • 1
  • timedelta can represent duration in days, hours, seconds so you can say days=90 for 90 days. How do you want to handle months with different # days (e.g. 1-Jan + 90 days is not 1-Mar) ? – CodeMonkey Feb 23 '22 at 20:31
  • See https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime – azro Feb 23 '22 at 20:34
  • Why do you expect to be able to add a `timedelta` to a string? – Pranav Hosangadi Feb 23 '22 at 20:42

2 Answers2

1

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
azro
  • 53,056
  • 7
  • 34
  • 70
  • if I put "2022-02-24" am getting "2022-05-25".Is to possible to get "2022-05-24" like this.Only month and year need to change – Treesa Feb 24 '22 at 04:25
1

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)
Corralien
  • 109,409
  • 8
  • 28
  • 52