Python | Sort list of dates given as strings
To sort a list of dates given as strings in Python, we can convert the date strings to datetime
objects for accurate comparison. Once converted, the list can be sorted using Python’s built-in sorted()
or list.sort()
functions. This ensures the dates are sorted chronologically.
Using pandas.to_datetime()
This method converts date strings to datetime
objects using pandas
, which is efficient for handling large datasets and supports various date formats. We can then sort the dates using sort_values()
.
import pandas as pd
# Example list of date strings
dates = ["24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997"]
# Convert the list of dates into a pandas Series
s1 = pd.Series(dates)
# Convert the strings to datetime objects and sort
s2 = s1.apply(pd.to_datetime, format='%d %b %Y').sort_values()
# Convert sorted datetime objects back to the string format
s3 = s2.dt.strftime('%d %b %Y').tolist()
print(s3)
Output
['11 Jun 1996', '01 Jan 1997', '12 Aug 2005', '24 Jul 2017', '25 Jul 2017', '01 Jan 2019']
Let’s understand other methods to sort list of dates:
Using datetime.strptime()
This method converts date strings into datetime
objects using Python’s datetime
module. It allows for precise date comparison and can be used with sorted()
to sort the list.
from datetime import datetime
# Example list of date strings
dates = ["24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997"]
# Sorting using sorted() and converting string to datetime object
s1 = sorted(dates, key=lambda x: datetime.strptime(x, '%d %b %Y'))
# Converting datetime objects back to string format
s2 = [datetime.strftime(datetime.strptime(d, '%d %b %Y'), '%d %b %Y') for d in s1]
print(s2)
Output
['11 Jun 1996', '01 Jan 1997', '12 Aug 2005', '24 Jul 2017', '25 Jul 2017', '01 Jan 2019']
Using list.sort()
This method sorts the list in place by converting date strings to datetime
objects, making the sorting process efficient for smaller datasets when we don’t need to preserve the original list.
from datetime import datetime
# Example list of date strings
dates = ["24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997"]
# Sorting the list in place using list.sort() and datetime conversion
dates.sort(key=lambda x: datetime.strptime(x, '%d %b %Y'))
# Output the sorted list
print(dates)
Output
['11 Jun 1996', '01 Jan 1997', '12 Aug 2005', '24 Jul 2017', '25 Jul 2017', '01 Jan 2019']