16

Given an array:

unsortedArray = [
  {'Email': 'jen@test.com', 'Created': '1/15/14 15:01'}, 
  {'Email': 'julia@test.com', 'Created': '1/16/14 18:21'}, 
  {'Email': 'andy@test.com', 'Created': '1/15/14 22:41'}, 
  {'Email': 'julia@test.com', 'Created': '1/16/14 18:20'}, 
  {'Email': 'victoria@test.com', 'Created': '1/16/14 23:05'}, 
  {'Email': 'lindsey@test.com', 'Created': '1/17/14 9:02'}, 
  {'Email': 'jim@test.com', 'Created': '1/17/14 11:28'}
]

How to sort this by 'Created' attribute, newest to oldest?

thedonniew
  • 213
  • 1
  • 3
  • 11

1 Answers1

36

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
)
dursk
  • 4,435
  • 2
  • 19
  • 30