Given a list of dates in string format, write a Python program to sort the list of dates in ascending order.
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
sort() (for in-place sorting) and
sorted() (returns a new sorted list) functions for sorting lists. But by default, these in-built sorting functions will sort the list of strings in alphabetical order which would result in a wrong order in our case. Hence, we need to pass a
key argument to tell the sorting function that we need to compare the list items in a particular way and sort them accordingly.
In Python, we have the
datetime module which makes date based comparison easier. The
datetime.strptime() function is used to convert a given string into datetime object. It accepts two arguments: date (string) and format (used to specify the format. for eg: %Y is used for specifying year) and returns a datetime object.
The formatting that we require for this problem is as follows:
%d ---> for Day %b ---> for Month %Y ---> for Year
Hence, we need to pass the
datetime object as the
key argument in the sorting function to tell the sorting function that it needs to compare the strings by converting them into dates and sort them in the increasing 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
- How to sort a list in C# | List.Sort() Method Set -2
- Python | Sort all sublists in given list of strings
- Python | Sort given list of strings by part of string
- Python program to find number of days between two given dates
- Python | How to sort a list of strings
- Sort numeric strings in a list in Python
- Python | Ways to sort list of strings in case-insensitive manner
- Comparing dates in Python
- Python | Difference between two dates (in minutes) using datetime.timedelta() method
- Formatting Dates in Python
- Matplotlib.dates.DateFormatter class in Python
- Matplotlib.dates.ConciseDateFormatter class in Python
- Matplotlib.dates.datestr2num() in Python
- Matplotlib.dates.epoch2num() in Python
- Matplotlib.dates.drange() in Python
- Matplotlib.dates.AutoDateFormatter class in Python
- Python | Filter a list based on the given list of strings
- Python | Remove empty strings from list of strings
- Python | Tokenizing strings in list of strings
- NLP | Using dateutil to parse dates.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.