How to Sort List by Date in Python?

By Hardik Savani October 30, 2023 Category : Python

Hello Guys,

In this tutorial, you will learn python list sort date. we will help you to give an example of how to sort list by date in python. I would like to show you how to sort list by datetime in python. you will learn python list sort datetime. So, let us see in detail an example.

This Python program is sorting a list of date strings in ascending order.

First, the program imports the datetime module from the datetime library.

Then, it defines a list called inputDateList, which consists of four date strings in the format 'dd-mm-yyyy'.

Next, the program uses the sort() function on the inputDateList. When sorting, it utilizes the lambda function as the key parameter to specify the comparison rule. The lambda function takes each date from the list and converts it into a datetime object using the strptime() function. The strptime() function parses the given date string according to the specified format ("%d-%m-%Y") and returns it as a datetime object.

Finally, the program prints the sorted list of dates by using the print() function, including a string message before the sorted list is printed.

Example:

main.py

# importing datetime
from datetime import datetime
  
# input list of date strings
inputDateList = ['21-06-2023', '11-06-2023', '07-06-2023', '01-06-2023']
  
# sorting the input list by formatting each date using the strptime() function
inputDateList.sort(key=lambda date: datetime.strptime(date, "%d-%m-%Y"))
  
# Printing the input list after sorting
print("List Sorting by Date:\n", inputDateList)

Output:

List Sorting by Date:
 ['01-06-2023', '07-06-2023', '11-06-2023', '21-06-2023']

I hope it can help you...

Tags :
Shares