-2

I have a list with date, I want to substract 5 years from it.

I have tried the below code but it's not working.

import datetime
from dateutil.relativedelta import relativedelta
s = ["2018-06-19"]
print(datetime.datetime.strptime(s[0], '%Y-%m-%d').strftime('%Y-%m-%d')-relativedelta(years=5))

What am i doing wrong?

Alan003
  • 79
  • 3
  • 9
  • You can look at this answer as I think this will solve your problem :https://stackoverflow.com/questions/765797/python-timedelta-in-years. If this URL is useful, please close your question as it is a duplicate. – Saurav Panda Jul 16 '20 at 15:35
  • 4
    Why do you turn it back into a string *before* trying to subtract from it? – jonrsharpe Jul 16 '20 at 15:35
  • 1
    You're immediately converting your `datetime` object back into a string, and *then* trying to subtract the `relativedelta` object from it. You need to do the subtraction before the `.strftime()`. – jasonharper Jul 16 '20 at 15:36
  • Thank you. It solved the issue. Quite silly. – Alan003 Jul 16 '20 at 15:40

1 Answers1

1
.strftime('%Y-%m-%d')

Returns a string, thus is cannot be substracted with a relativedelta. Datetime objects can be substracted. Hence, convert your date to string after you do the substraction

print((datetime.datetime.strptime(s[0], '%Y-%m-%d')-relativedelta(years=5)).strftime('%Y-%m-%d'))
Codigo Morsa
  • 820
  • 7
  • 14