Python - Find number of days between two sting dates

  • To find the number of days between 2 dates in python, we just need to find the difference as below.

    Copied
    from datetime import datetime
    
    date1 = datetime(2022, 1, 15)
    date2 = datetime(2022, 5, 25)
    
    print((date2 - date1).days)
    
    Output:
      130
  • If dates are in string format, we will have to convert those before finding the difference.
    This sample uses date in mm-dd-yy format.
    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 = "03-14-22"
    
    formatteddate1 = datetime.strptime(stringdate1, '%m-%d-%y')
    formatteddate2 = datetime.strptime(stringdate2, '%m-%d-%y')
    
    print((formatteddate2 - formatteddate1).days)
    
    Output:
      17
Absolute Code Works - Python Topics