Python | Sort list of dates as strings



Examples :

Input: dates = [“24 Jul 2017”, “25 Jul 2017”, “11 Jun 1996 ”,“ 01 Jan 2019 ”,“ 12 Aug 2005 ”,“ 01 Jan 1997 ”]

Output: 01 Jan 2007
10 Jul 2016
2 Dec 2017
11 Jun 2018
23 Jun 2018
01 Jan 2019

Suitable:
In Python we can use the functions sort () (for sorting in place) and sorted () (returns a new sorted list) to sort the lists. But by default, these built-in sort functions will sort the list of strings alphabetically, which in our case will result in the wrong order. Therefore, we need to pass a key argument to tell the sorting function that we need to compare the elements of the list in a specific way and sort them accordingly.

In Python, we have a module datetime which makes comparison based on date easier. The datetime.strptime () function is used to convert a given string to a datetime object. It takes two arguments, (string) and (used to specify the format. For example:% Y is used to specify the year) and returns a datetime object.

Syntax :

 datetime.strptime (date, format) 

The formatting we need for this problem is as follows:

 % d  --- & gt ; for Day % b  --- & gt; for Month % Y  --- & gt; for Year 

Therefore, we need to pass a datetime object as a key argument to the sort function to tell the sort function to compare strings by converting them into dates and sort them in ascending order.

Below is the implementation of the above approach:

# Python3 program for sorting a list of dates
# given in string format

 
# Import datetime module

from datetime import datetime

 
# Function for printing the data stored in the list

def printDates (dates): 

  

for i in range ( len (dates)): 

print (dates [i]) 

 

  

if __ name__ = = "__ main__"

  

  dates =   [ " 23 Jun 2018 " , " 2 Dec 2017 " , "11 Jun 2018"

  "01 Jan 2019" , "10 Jul 2016" , "01 Jan 2007"

 

# Sort the list in ascending date order

dates.sort (key = lambda date: datetime.strptime (date, `% d% b % Y` ))

 

# Print dates in sorted order

printDates (dates) 

Exit :

 01 Jan 2007 10 Jul 2016 2 Dec 2017 11 Jun 2018 23 Jun 2018 01 Jan 2019