Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sort datetime in str format with lambda

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.

like image 593
user1757703 Avatar asked Nov 21 '25 03:11

user1757703


2 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.

like image 134
Martijn Pieters Avatar answered Nov 22 '25 16:11

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)
like image 25
Wolph Avatar answered Nov 22 '25 16:11

Wolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!