Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of objects by datetime in Python? [duplicate]

Tags:

python

sorting

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?

like image 743
thedonniew Avatar asked Nov 04 '15 01:11

thedonniew


People also ask

How do you sort a datetime array in Python?

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.

How do you sort multiple items in Python?

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.


1 Answers

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
)
like image 80
dursk Avatar answered Sep 28 '22 09:09

dursk