In this tutorial we will learn how to sort list by date in Python.
How to sort list by date in Python
To sort a list of dates in Python, you can use the sorted()
function or the sort()
method of a list. Here's how you can do it:
Suppose you have a list of dates in string format like this:
date_list = ["2023-09-15", "2022-03-10", "2021-07-25", "2023-01-05"]
You can sort this list in ascending order (from the oldest date to the newest date) using the sorted()
function like this:
sorted_date_list = sorted(date_list)
print(sorted_date_list)
Alternatively, you can use the sort()
method to sort the list in-place:
date_list.sort()
print(date_list)
If you want to sort the list in descending order (from the newest date to the oldest date), you can use the reverse
parameter of the sorted()
function or the sort()
method:
Using sorted()
:
sorted_date_list_desc = sorted(date_list, reverse=True)
print(sorted_date_list_desc)
Using sort()
:
date_list.sort(reverse=True)
print(date_list)
If your dates are stored as datetime objects instead of strings, you can still use the same approach to sort them.
Here's an example of how to sort a list of datetime objects:
from datetime import datetime
date_list = [datetime(2023, 9, 15), datetime(2022, 3, 10), datetime(2021, 7, 25), datetime(2023, 1, 5)]
sorted_date_list = sorted(date_list)
print(sorted_date_list)
And to sort them in descending order:
sorted_date_list_desc = sorted(date_list, reverse=True)
print(sorted_date_list_desc)
This will give you the list of dates sorted by date in either ascending or descending order, depending on your preference.