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
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.
datetime.strptime (date, format)
The formatting we need for this problem is as follows:
% d --- & gt ; for Day % b ---" for Month % Y ---" 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:
01 Jan 2007 10 Jul 2016 2 Dec 2017 11 Jun 2018 23 Jun 2018 01 Jan 2019