How to sort a Python date string list?

PythonServer Side ProgrammingProgramming

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object. 

example

from datetime import datetime
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
print(my_dates)

Output

This will give the output −

['7-Mar-17', '25-Mar-17', '1-Nov-18', '5-Nov-18']
raja
Published on 08-Jan-2018 09:54:09
Advertisements