How to Sort a String Date in Python?

Estimated read time 2 min read

In Python, you can sort a string date using the datetime module and the sorted() function. Here is an example code that sorts a string date:

from datetime import datetime

# Create a sample list of dates
dates = ["2022-03-25", "2022-03-24", "2022-03-23"]

# Sort the list of dates
sorted_dates = sorted(dates, key=lambda x: datetime.strptime(x, "%Y-%m-%d"))

# Print the sorted list of dates
print(sorted_dates)

In this code, we first import the datetime module using the import statement. We then create a sample list of dates dates (which are in the format “YYYY-MM-DD”).

We then use the sorted() function to sort the list of dates based on their values as datetime objects. We pass a lambda function as the key parameter of the sorted() function, which converts each date string to a datetime object using the strptime() method of the datetime module. The strptime() method takes two arguments: the date string and a format string that specifies the format of the date string (in this case, “%Y-%m-%d” for “YYYY-MM-DD”).

We then print the sorted list of dates using the print() function. The output of this code is ['2022-03-23', '2022-03-24', '2022-03-25'], which is the sorted list of dates in ascending order.

Note that you can customize the date format and the sorting order by using different format strings and by changing the key function accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply