How to Sort List by Date in Python?
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.
# 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)
List Sorting by Date: ['01-06-2023', '07-06-2023', '11-06-2023', '21-06-2023']
I hope it can help you...
We are Recommending you
- How to Get Content from URL in Python?
- How to Get Last 2 Digits of a Number in Python?
- Sum of First and Last Digit of a Number in Python
- Python Get First and Last Digit of a Number Example
- How to Get the Last Digit of a Number in Python?
- How to Get the First Digit of a Number in Python?
- Python Remove All Decimals from Number Example
- Python Openpyxl Read Excel File Example
- Python Openpyxl Create Excel File with Multiple Sheets
- How to Add Header in CSV File using Python?
- Python Create Text File in Specific Directory Example
- How to Capitalize String in Python?
- Python Delete Files with Specific Extension Example