-3

Issue

Below is a list of dates in the string format(MM/DD/YYYY).
I'm trying to sort them in ascending order(oldest to most-recent date) using .sort() but getting wrong results.

List before sort

listOfDates = ['07/25/2022', '07/19/2022', '04/19/2022', '02/18/2022', '01/18/2022', '10/20/2021', '10/27/2021', '11/26/2021', '12/23/2021', '01/05/2022', '01/07/2022', '01/18/2022', '01/21/2022', '01/24/2022', '02/24/2022', '02/25/2022', '03/16/2022', '03/25/2022', '04/29/2022', '05/10/2022', '05/11/2022', '05/31/2022', '06/08/2022', '06/10/2022', '06/13/2022', '06/14/2022', '07/14/2022']

Results using listOfDates.sort()

The problem here is that it appears to be sorting by month and not chronologically. Notice it starts at 01/05/2022 and goes up to 07/25/2022 and then continues at 10/20/2021 until ending 12/23/2021

['01/05/2022', '01/07/2022', '01/18/2022', '01/18/2022', '01/21/2022', '01/24/2022', '02/18/2022', '02/24/2022', '02/25/2022', '03/16/2022', '03/25/2022', '04/19/2022', '04/29/2022', '05/10/2022', '05/11/2022', '05/31/2022', '06/08/2022', '06/10/2022', '06/13/2022', '06/14/2022', '07/14/2022', '07/19/2022', '07/25/2022', '10/20/2021', '10/27/2021', '11/26/2021', '12/23/2021']

Expecting

That the dates are ordered in the list by descending order with the first element starting 10/20/2021 and the final element in the list is 07/25/2022

4
  • 1
    Well, you're sorting strings, not dates. Commented Jul 27, 2022 at 14:41
  • You are sorting them according to their string values. Instead, sort them according to their date value. You can parse them to dates using datetime.strptime docs.python.org/3/library/… Commented Jul 27, 2022 at 14:42
  • Why do you expect strings to be sorted as dates? If you want to sort them as dates, specify a key argument to .sort() which converts the string to a date. docs.python.org/3/howto/sorting.html#key-functions Commented Jul 27, 2022 at 14:42
  • I recommend using the datetime module. Personally, I would iterate through your list and convert each date to a datetime object in a new list. Then, you can use sort functions in the module that intelligently will base the sort on chronology. Commented Jul 27, 2022 at 14:44

1 Answer 1

0

You can do something like this

import datetime

sortedDates = sorted([datetime.datetime.strptime(item, '%m/%d/%Y') for item in listOfDates])

[item.strftime('%m/%d/%Y') for item in sortedDates]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.