Given an array:
unsortedArray = [
{'Email': '[email protected]', 'Created': '1/15/14 15:01'},
{'Email': '[email protected]', 'Created': '1/16/14 18:21'},
{'Email': '[email protected]', 'Created': '1/15/14 22:41'},
{'Email': '[email protected]', 'Created': '1/16/14 18:20'},
{'Email': '[email protected]', 'Created': '1/16/14 23:05'},
{'Email': '[email protected]', 'Created': '1/17/14 9:02'},
{'Email': '[email protected]', 'Created': '1/17/14 11:28'}
]
How to sort this by 'Created' attribute, newest to oldest?
To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.
Use sorted() and a lambda expression to sort a list by two fields. Call sorted(a_list, key = k) with k as lambda x: x[i], x[j] to sort list by the i -th element and then by the j -th element.
You can use the built-in sorted
function, along with datetime.strptime
from datetime import datetime
sortedArray = sorted(
unsortedArray,
key=lambda x: datetime.strptime(x['Created'], '%m/%d/%y %H:%M'), reverse=True
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With