Python - Find biggest of string dates
-
List of datetime objects
We can use max function to find biggest of a list of datetime objects.
Output:Copiedfrom 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("Biggest Date: " + str(max(datelist)))
Biggest Date: 2022-01-18 00:00:00 -
List of string dates in same format
For a list of string dates which are in same format, we just need to use strptime() to convert string to datetime objects and then apply max function.
Output:Copiedfrom 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("Biggest Date: " + str(max(datelist)))
Biggest Date: 2021/10/15 -
List of string dates in different format
If the list contains string dates in multiple formats, we will have to loop through each item and use a try...except block to find the correct format.
A function formatDates() is created here to handle the logic.Output:Copiedfrom 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("Biggest Date: " + str(max(dtlist)))
Biggest Date: 2022-01-18 00:00:00