Python - Find number of months completed between two string dates

  • For 2 given dates, we are going to check how many months have been completed using Python.
    To calculate this, we have to consider the days part of both the dates as well. If the day of the second date is less than the first date, we will have to reduce 1 from the month difference.
    Refer sample below.

    Copied
    from datetime import datetime
    
    date1 = datetime(2022, 1, 15)
    date2 = datetime(2022, 5, 25)
    
    monthsbetween = 0
    if(date2.day >= date1.day):
        monthsbetween = date2.month - date1.month
    else:
        monthsbetween = (date2.month - date1.month) - 1
    
    print(monthsbetween)
    
    Output:
      4

    In the above sample, if date2 day is less than 15, number of months completed is 3.

  • For dates in string format, convert 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 = "02-25-22"
    stringdate2 = "07-25-22"
    
    formatteddate1 = datetime.strptime(stringdate1, '%m-%d-%y')
    formatteddate2 = datetime.strptime(stringdate2, '%m-%d-%y')
    
    monthsbetween = 0
    if(formatteddate2.day >= formatteddate1.day):
        monthsbetween = formatteddate2.month - formatteddate1.month
    else:
        monthsbetween = (formatteddate2.month - formatteddate1.month) - 1
    
    print(monthsbetween)
    
    Output:
      5
Absolute Code Works - Python Topics