I am trying to program a function that returns me the difference in years given an specific date format,
which is: "01/%m/%Y":
Here's the code I am using:
import datetime as datetime
###################### function to return difference in years ####################
def years_between(start_year, end_year):
start_year = datetime.strptime(start_year, "01/%m/%Y")
end_year = datetime.strptime(end_year, "01/%m/%Y")
return abs((end_year - start_year).years)
When tested it returns:
years_between("01/10/1900", "01/10/2000")
AttributeError: 'datetime.timedelta' object has no attribute 'years'
Expected function output would be an integer, in the above case would be 100
Is there any other way to correct this function?
from datetime import datetime
def years_between(start_year, end_year):
start_year = datetime.strptime(start_year, "%d/%m/%Y")
end_year = datetime.strptime(end_year, "%d/%m/%Y")
return abs(end_year.year - start_year.year)
print(years_between("01/10/1901", "01/10/2000"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With