Python - Compare two string dates in different formats

  • If both dates are datetime objects

    Comparison or Logical operators can be applied on 2 datetime objects as below.
    Results will be either True or False.

    Copied
    from datetime import datetime
    
    dt1 = datetime(2020, 10, 15, 0, 0)
    dt2 = datetime(2021, 12, 11, 0, 0)
    
    print(dt1 == dt2)
    print(dt1 < dt2)
    print(dt1.year == dt2.year)
    
    #Returns biggest number from each part
    print(dt1 and dt2)
    
    Output:
      False
      True
      True
      2021-12-11 00:00:00
  • If both are string dates

    If dates are in string format, first convert to the datetime object before doing the comparison. Otherwise the dates will be treated as strings and we will not get the desired output.

    As seen in the below sample, both dates are same, but formatted differently. When we do a comparison directly without converting to datetime, result is False, even-though both dates are same. So, always convert string dates to datetime, before doing comparison.

    Copied
    from datetime import datetime
    
    #Both dates are same. But formatted in different ways
    sdt1 = '2020/10/15'
    sdt2 = '10-15-2020'
    
    dt1 = datetime.strptime(sdt1, '%Y/%m/%d')
    dt2 = datetime.strptime(sdt2, '%m-%d-%Y')
    
    #False, because string comparison is happening
    print(sdt1 == sdt2)
    #Returns True
    print(dt1 == dt2)
    
    Output:
      False
      True
Absolute Code Works - Python Topics