1

I have a list of email objects. It contains DateTime in the following format:

Thu, 17 Dec 2020 15:30:15 +0100

When I try to sort the list using sorted(), it only sorts by the time.

sorted_emails = sorted(emails,key=lambda email: email['Date'],reverse=True)

for item in sorted_emails:
    print(item['Date'])

Outputs:

Wed, 16 Dec 2020 21:59:45 +0100
Wed, 16 Dec 2020 21:58:22 +0100
Wed, 16 Dec 2020 12:29:39 +0100
Wed, 16 Dec 2020 12:29:13 +0100
Wed, 16 Dec 2020 12:28:41 +0100
Wed, 16 Dec 2020 12:26:50 +0100
Wed, 16 Dec 2020 12:26:17 +0100
Wed, 16 Dec 2020 12:25:57 +0100
Thu, 17 Dec 2020 15:30:15 +0100
Sat, 12 Dec 2020 21:17:35 +0100

How would I make it sort accounting for the date as well?

  • 3
    Parse the date with [strptime()](https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime) and use that as a sort key. – Klaus D. Dec 17 '20 at 15:06
  • If you have the possibility to modify your dataset, try to use ISO 8601 format (`yyyy-MM-dd HH:mm:ss`)if you have to serialize datetime to string, it has the advantage that the natural string sort will also be the date time sort. – Pac0 Dec 17 '20 at 15:09
  • to elaborate on Klaus' comment: see https://stackoverflow.com/questions/10494312/parsing-time-string-in-python – Pac0 Dec 17 '20 at 15:11

2 Answers2

1

You have to parse your dates and use datetime.datetime.strptime. Try something like this:

import datetime
dateformat =  "%a, %d %b %Y %H:%M:%S %z"
for email in emails:
    email['parsed_date'] = datetime.datetime.strptime(email['date'], dateformat)

and then sort by email['parsed_date'].

For the syntax of the "formatting directive", see here https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

gpweb
  • 143
  • 1
  • 5
-2

Okay so I quickly figured out that I have to only take the substring of the date and time, or else it will sort by the day of the week

sorted_emails = sorted(emails,key=lambda email: email['Date'][5:], reverse=True)

this solved the issue

  • 1
    This is going to sort `01 Jan` after `01 Feb`. And the most significant year becomes least significant. – Klaus D. Dec 17 '20 at 15:07