Python: Sort datetime in str format with lambda

Question:

I am using sorted(response, key=lambda k: k['createDate'], reverse=False) to get the most recent list members sorted to the front of the list. The problem is that my datetime is in string format %Y-%m-%d %I:%M:%S %p. If I do this sort, it will sort via string comparison and not datetime comparison. How do I work around this issue?

EDIT: Forgot to mention I am usin Python 3.4.

Asked By: user1757703

||

Answers:

You’ll have to parse your values to datetime objects in your key function:

from datetime import datetime

sorted(
    response,
    key=lambda k: datetime.strptime(k['createDate'], '%Y-%m-%d %I:%M:%S %p'),
    reverse=True,
)

Had your date format been slightly different, you could have used straight string sorting; ISO8601 dates (formatted to '%Y-%m-%d %H:%M:%S') are lexicographically sortable.

I also changed the sort order; you want the order reversed, the most recent datetime value will be higher than those that precede it:

>>> datetime(2014, 6, 11, 17, 16, 10) > datetime(2008, 9, 15, 12, 00, 00)
True

so the most recent values would be sorted to be the last elements if you don’t reverse the sort.

Answered By: Martijn Pieters

Just parse the results in your key function, something like this should do:

import datetime
def parse_timestamp_from_response(response):
    return datetime.datetime.strptime(response['createDate'], '%Y-%m-%d %I:%M:%S %p')

sorted(response, key=parse_timestamp_from_response, reverse=False)
Answered By: Wolph
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.