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