Python - Filter a list of string dates which are in different formats

  • For a list of datetime objects, use List Comprehensions directly to filter based on the condition.
    Below example filters the dates after 2020 and then converts to a string format.

    Copied
    from datetime import datetime
    
    initialDates = [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)]
    
    filtereddates = [dt for dt in initialDates if dt.year > 2020]
    filtdates = [datetime.strftime(dt, '%Y/%m/%d %H:%M:%S') for dt in filtereddates]
    print(filtdates)
    
    Output:
      ['2021/12/22 00:00:00', '2022/01/18 00:00:00', '2021/10/15 08:40:50']
  • String dates list in same format

    Convert the list to datetime objects list using strptime() and then apply filter condition.

    Copied
    from datetime import datetime
    
    #Date in string format
    datelist = ['2020/10/15', '2019/10/15', '2021/10/15', '2022/02/05']
    #Convert to datetime objects list
    dtlist = [datetime.strptime(dt, '%Y/%m/%d') for dt in datelist]
    
    #Filter conditions
    filtereddates = [dt for dt in dtlist if dt.year > 2020]
    #Convert output to string format, if needed
    filtdates = [datetime.strftime(dt, '%Y/%m/%d %H:%M:%S') for dt in filtereddates]
    print(filtdates)
    
    Output:
      ['2021/10/15 00:00:00', '2022/02/05 00:00:00']
  • String dates list in different format

    For a list of string dates in multiple formats, loop through each item and use a try...except block to find the correct format.
    Then apply the required filter.

    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
    
    #Input
    datelist = ['2020/10/15', '12-22-21', '22.01.18', '10-15-2021 08:40:50', '2018.08.14 22:35']
    #Convert string dates to datetime
    dtlist = formatDates(datelist)
    
    #Filter conditions
    filtereddates = [dt for dt in dtlist if dt.year > 2020]
    #Convert output to string format if needed
    filtdates = [datetime.strftime(dt, '%Y/%m/%d %H:%M:%S') for dt in filtereddates]
    print(filtdates)
    
    Output:
      ['2021/12/22 00:00:00', '2022/01/18 00:00:00', '2021/10/15 08:40:50']
Absolute Code Works - Python Topics