Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set a function that returns the difference in years in python?

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?

like image 898
AlSub Avatar asked Aug 11 '26 05:08

AlSub


1 Answers


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"))
like image 151
Leemosh Avatar answered Aug 13 '26 22:08

Leemosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!