Python - Sorting a list of dates in different formats

  • If we have a list of string dates which are in same format, sorting these items are easy. We just need to convert those to date objects using strptime() function and then sort using sorted() function.

    If needed, we can convert dates back to string format using strftime().
    Run below sample to see the output.

    Copied
    from datetime import datetime
    
    datestosort = ['2020/10/15', '2019/10/15', '2021/10/15']
    dtlist = [datetime.strptime(dt, '%Y/%m/%d') for dt in datestosort]
    
    sorteddates = [datetime.strftime(dt, '%Y/%m/%d') for dt in sorted(dtlist)]
    print(sorteddates)
    
    Output:
      ['2019/10/15', '2020/10/15', '2021/10/15']
  • There may be scenarios in which the list contains dates with multiple formats.
    Here, we will not be able to apply the strptime() directly on string dates.
    Below is the easiest and fastest way to handle this.

    The only challenge here is to know in advance of all the expected formats and keep it as a list.
    Then just loop through the items and use a try...except block to find the correct format of each dates.
    If any format is not included in our expected format list, such dates will not get added to the final output.

    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
    
    datestosort = ['2020/10/15', '12-22-21', '22.01.18', '10-15-2021 08:40:50', '2018.08.14 22:35']
    dtlist = formatDates(datestosort)
    
    sorteddates = [datetime.strftime(dt, '%Y/%m/%d %H:%M:%S') for dt in sorted(dtlist)]
    print(sorteddates)
    
    Output:
      ['2018/08/14 22:35:00', '2020/10/15 00:00:00', '2021/10/15 08:40:50', '2021/12/22 00:00:00', '2022/01/18 00:00:00']
Absolute Code Works - Python Topics