Python - Find smallest of string dates

  • Smallest of datetime objects

    Finding smallest of a list of datetime objects is easy.
    Apply min function on the list to get the output.

    Copied
    from datetime import datetime
    
    datelist = [datetime(2020, 10, 15, 0, 0), datetime(2021, 12, 22, 0, 0), datetime(2022, 1, 18, 0, 0), datetime(2021, 10, 15, 8, 40, 50), datetime(2018, 8, 14, 22, 35)]
    print("Smallest Date: " + str(min(datelist)))
    
    Output:
      Smallest Date: 2018-08-14 22:35:00
  • Smallest of string dates in same format

    If the list contains string dates in the same format, use strptime() function to change string to datetime and use min function.

    Copied
    from datetime import datetime
    
    datelist = ['2020/10/15', '2019/10/15', '2021/10/15']
    dtlist = [datetime.strptime(dt, '%Y/%m/%d') for dt in datelist]
    print("Smallest Date: " + str(min(datelist)))
    
    Output:
      Smallest Date: 2019/10/15
  • Smallest of string dates in different format

    For a list with string dates in different formats, strptime() can't be used directly.
    Identify the expected formats and keep it as an array as below.
    Then loop through the items to apply the right format.
    Finally, find the smallest of the dates.

    Copied
    from datetime import datetime
    
    def formatDates(datestosort):
        formatlist = ['%Y/%m/%d', '%m-%d-%y', '%y.%m.%d', '%m-%d-%Y %H:%M:%S', '%Y.%m.%d %H:%M']
    
        newdtlist = []
        for dt in datestosort:
            for fl in formatlist:
                try:
                    newdtlist.append(datetime.strptime(dt, fl))
                    break
                except:
                    pass
            
        return newdtlist
    
    datelist = ['2020/10/15', '12-22-21', '22.01.18', '10-15-2021 08:40:50', '2018.08.14 22:35']
    dtlist = formatDates(datelist)
    print("Smallest Date: " + str(min(dtlist)))
    
    Output:
      Smallest Date: 2018-08-14 22:35:00
Absolute Code Works - Python Topics