How to sort a Python date string list?


In this article, we will show you how to sort a Python date string list. Now we see 3 methods to accomplish this task−

Now we see 2 methods to accomplish this task−

  • Using sort() and lambda functions

  • Using sort() function

  • Using sorted function

Method 1: Using sort() and lambda functions

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Use the import keyword, to import the datetime from datetime module (To work with dates and times, Python has a module called datetime).

  • Create a variable to store the input list of date strings

  • Sort the list of dates using the sort() function by passing the argument as the lambda function. Here in the lambda function, we converted each date to date object using the strptime() function (formats a time stamp in string format into a date−time object).

  • Print the input list of date strings after sorting.

Example

The following program returns the sorted list of an input list of date strings using the datetime module−

# importing datetime from datetime import datetime # input list of date strings inputDateList = ['06-2014', '08-2020', '4-2003', '04-2005', '10-2002', '12-2021'] # sorting the input list by formatting each date using the strptime() function inputDateList.sort(key=lambda date: datetime.strptime(date, "%m-%Y")) # Printing the input list after sorting print("The input list of date strings after sorting:\n", inputDateList)

Output

On executing, the above program will generate the following output −

The input list of date strings after sorting:
['10-2002', '4-2003', '04-2005', '06-2014', '08-2020', '12-2021']

Method 2: Using sort() function

The sort() method sorts the original list in place. It signifies that the sort() method changes the order of the list's elements.

By default, the sort() method uses the less−than operator (<) to sort the entries of a list i.e., in ascending order. In other words, it prioritizes lesser elements above higher ones.

To sort elements from highest to lowest (descending order), use the reverse=True parameter in the sort() method.

list.sort(reverse=True)

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Create a variable to store the input list of date strings

  • Create a function that accepts the input list as an argument.

  • Use the split() function (splits a string into a list. We can define the separator; the default separator is any whitespace), to split the list of elements based on the '−' separator.

  • Use sort() function, to sort the input list of date strings by passing the key as the function name as an argument to it.

  • Print the input list of date strings after sorting.

Example

The following program returns the sorted list of an input list of date strings using the sort() function −

# input list of date strings inputDateList = ['06-2014', '08-2020', '4-2003', '04-2005', '10-2002', '12-2021'] # creating a function that accepts the input list as an argument def sortDates(datesList): # splitting the list of elements based on the '-' separator(as the date is separated by - symbol ex 06-2014) split_up = datesList.split('-') # returning the year, the month of input list elements # Here split_up[1] gives the year and split_up[0] gives month return split_up[1], split_up[0] # sorting the input list of date strings using the sort() function # here the key is the function name inputDateList.sort(key=sortDates) # Printing the input list after sorting print("The input list of date strings after sorting:\n", inputDateList)

Output

The input list of date strings after sorting:
['10-2002', '4-2003', '04-2005', '06-2014', '08-2020', '12-2021']

We took a list of dates as input and then wrote a function that takes a list element as an argument (date) and then splits the date into separate elements month and year and returns it. We used the sort() function on the given list and passed the function name as an argument. The result sort() function applies the function to each element and sorts them accordingly.

Method 3: Using sorted() function

The sorted() function returns a sorted list of the iterable object given.

You can choose between ascending and descending order. Numbers are sorted numerically, while strings are arranged alphabetically.

Syntax

sorted(iterable, key=key, reverse=reverse)

Parameters

  • iterable- It is a sequence.

  • key - A function that will be executed to determine the order. The default value is None.

  • reverse - A Boolean expression. True sorts ascending, False sorts descending. The default value is False.

Algorithm (Steps)

Use sorted() function, to sort the input list of date strings by passing the list, key as the function name as arguments to it and print the output

Example

The following program returns the sorted list of an input list of date strings using the sorted function −

inputDateList = ['06-2014', '08-2020', '4-2003', '04-2005', '10-2002', '12-2021'] def sortDates(datesList): # splitting the list of elements based on the '-' separator split_up = datesList.split('-') # returning the year, the month of input list elements # Here split_up[1] gives the year and split_up[0] gives month return split_up[1], split_up[0] print("The input list of date strings after sorting:\n") # sorting the input list of date strings using the sorted function # here the key is the function name print(sorted(inputDateList, key=sortDates))

Output

The input list of date strings after sorting:
['10-2002', '4-2003', '04-2005', '06-2014', '08-2020', '12-2021']

It is the same as in the previous method, except that the sorted() function accepts the input list and the function as arguments. We used the key as the function name in this case because the sorted() function takes every date, splits it, and sorts it based on it.

Conclusion

We learned how to sort a list of dates using three different methods in this article. We also learned how to use the split() function to divide a given date into months and years.

Updated on: 02-Nov-2023

30K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements