How to sort python dictionary by datetime key?

Question:

I have a dictionary like below:

dt = {'2016-12-15 18:12:17': 1, '2016-12-15 17:40:39': 1, '2016-12-15 15:53:42': 1, '2016-12-15 15:51:41': 1, '2016-12-15 15:49:55': 1, '2016-12-15 15:49:54': 1, '2016-12-15 15:48:05': 1, '2016-12-15 15:27:38': 1, '2016-12-15 09:05:03': 1, '2016-12-15 08:43:45': 1, '2016-12-15 07:29:15': 1, '2016-12-15 05:56:58': 1, '2016-12-14 14:33:31': 1, '2016-12-14 14:33:30': 1, '2016-12-14 14:33:29': 1, '2016-12-14 14:33:28': 1, '2016-12-14 13:24:55': 1, '2016-12-14 13:15:51': 1, '2016-12-14 13:05:38': 1, '2016-12-14 12:58:47': 1}

I want to sort the dictionary on datetime key.

I tried :

dt = ordereddict.OrderedDict()

But it is not working please help.

Asked By: Darshit Rama

||

Answers:

Convert the keys in dt into datetime objects, for instance, using dateutil.parser.parse,

from dateutil.parser import parse
from collections import OrderedDict

new_d = OrderedDict(sorted(dt.items(), key=lambda x: parse(x[0])))

print(new_d)
'''
OrderedDict([   ('2016-12-14 12:58:47', 1), 
                ('2016-12-14 13:05:38', 1), 
                ('2016-12-14 13:15:51', 1), 
                ('2016-12-14 13:24:55', 1), 
                ('2016-12-14 14:33:28', 1), ('2016-12-14 14:33:29', 1), ('2016-12-14 14:33:30', 1), ('2016-12-14 14:33:31', 1), ('2016-12-15 05:56:58', 1), ('2016-12-15 07:29:15', 1), ('2016-12-15 08:43:45', 1), ('2016-12-15 09:05:03', 1), ('2016-12-15 15:27:38', 1), ('2016-12-15 15:48:05', 1), ('2016-12-15 15:49:54', 1), ('2016-12-15 15:49:55', 1), ('2016-12-15 15:51:41', 1), ('2016-12-15 15:53:42', 1), ('2016-12-15 17:40:39', 1), ('2016-12-15 18:12:17', 1)])

'''

In your specific case, as pointed by @AndreaCorbellini, sorting strings directly works fine, i.e.

new_d = OrderedDict(sorted(dt.items()))
Answered By: SparkAndShine

This works and doesn’t need dateutil:

import datetime
sorted(dt.items(), key=lambda x: datetime.datetime.fromisoformat(x[0]))
[('2016-12-15 18:12:17', 1), ('2016-12-15 17:40:39', 1), ('2016-12-15 15:53:42', 1), ('2016-12-15 15:51:41', 1), ('2016-12-15 15:49:55', 1), ('2016-12-15 15:49:54', 1), ('2016-12-15 15:48:05', 1), ('2016-12-15 15:27:38', 1), ('2016-12-15 09:05:03', 1), ('2016-12-15 08:43:45', 1), ('2016-12-15 07:29:15', 1), ('2016-12-15 05:56:58', 1), ('2016-12-14 14:33:31', 1), ('2016-12-14 14:33:30', 1), ...]

If you want the oldest date first, just provide reverse=True to sorted

Answered By: NotoriousPyro
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.