0

I have a list of "snapshots" which look like this

{ description: "sdoiajosdi", "startDate": datetime.datetime(2021, 7, 16, 22, 47, 50, 609000, tzinfo=tzlocal()), Tags: [ {'sdklapsijd':'asdjiosoid'}], ownerId: "osjdaiosjd" }

These are stored in a python list. Is there a way I can sort ascending or descending based on the 'startDate' property for each item in the list? So if I have 100 snapshot objects, with differing datetime.datetime properties, can I use this as the 'sorting key?' How can I do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30
  • Of course. Just provide an appropriate `key=` argument to the `sort()` method. – Barmar Jul 28 '21 at 20:48
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – wjandrea Jul 28 '21 at 20:51

1 Answers1

1

As datetime objects are comparable, you should just be able to sort the list with:

sorted(snapshots, key=lambda x: x["startDate"])
wjandrea
  • 28,235
  • 9
  • 60
  • 81
sj95126
  • 6,520
  • 2
  • 15
  • 34