Python - Find number of years completed between two sting dates

  • To find the number of completed years between two dates using Python, we will also have to check months and days.
    Refer sample below.

    Copied
    from datetime import datetime
    
    date1 = datetime(2022, 4, 15)
    date2 = datetime(2025, 5, 25)
    
    yearsbetween = 0
    if(date2.month > date1.month):
        yearsbetween = date2.year - date1.year
    elif(date2.month < date1.month):
        yearsbetween = (date2.year - date1.year) - 1
    else:
        if(date2.day >= date1.day):
            yearsbetween = date2.year - date1.year
        else:
            yearsbetween = (date2.year - date1.year) - 1
    
    print(yearsbetween)
    
    Output:
      3

    Try changing month and days of date2 to see different outputs.
    If date2 month changed to 3, output becomes 2.
    If date2 month changed to 4, and day >= 15, output becomes 3.
    If date2 month changed to 4, and day < 15, output becomes 2.

  • String dates are to be converted to datetime object before finding the difference, as in sample below.
    For more samples on string to date conversion refer Convert String to Datetime - All Formats

    Copied
    from datetime import datetime
    
    stringdate1 = "04-15-22"
    stringdate2 = "05-25-25"
    date1 = datetime.strptime(stringdate1, '%m-%d-%y')
    date2 = datetime.strptime(stringdate2, '%m-%d-%y')
    
    yearsbetween = 0
    if(date2.month > date1.month):
        yearsbetween = date2.year - date1.year
    elif(date2.month < date1.month):
        yearsbetween = (date2.year - date1.year) - 1
    else:
        if(date2.day >= date1.day):
            yearsbetween = date2.year - date1.year
        else:
            yearsbetween = (date2.year - date1.year) - 1
    
    print(yearsbetween)
    
    Output:
      3
Absolute Code Works - Python Topics