-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
  • 81
  • 1
  • 8
  • 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

2 Answers2

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
  • 737
  • 5
  • 14
1

You're changing your time back to string before removing the years? Just switch the 2 statements.

print((datetime.datetime.strptime(s[0], '%Y-%m-%d') - relativedelta(years=5)).strftime('%Y-%m-%d'))

Just split the statements and it will be easier to read.

x = datetime.datetime.strptime(s[0], '%Y-%m-%d')
x_minus_years = x - relativedelta(years = 5)
print(x_minus_years.strftime('%Y-%m-%d'))
bwuak
  • 11
  • 3