Smit Shilu
Smit Shilu

Reputation: 355

Python Dict() sorting according to datetime

I have one file with so many values those are as below

{'Name':'xyz','Date':'Thu Jun 26 13:14:17 +0000 2008'}
{'Name':'xyz','Date':'Thu Jun 19 13:14:17 +0000 2009'}
{'Name':'xyz','Date':'Thu Jun 26 13:15:17 +0000 2008'}

How to sort these values according to date and time?

Upvotes: 1

Views: 1137

Answers (3)

jfs
jfs

Reputation: 414079

You could use email package from stdlib, to parse the date format into "seconds since the Epoch":

>>> from email.utils import parsedate_tz, mktime_tz
>>> mktime_tz(parsedate_tz('Thu Jun 26 13:14:17 +0000 2008'))
1214486057

It is easy to sort dicts by Date field:

>>> sorted(dicts, key=lambda d: mktime_tz(parsedate_tz(d['Date'])))
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]

To load json objects from the file, you could use code from @ShadowRanger's answer.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155323

If the file has these one per line, you'll need to convert to real dicts, e.g. with json.loads or ast.literal_eval, then sort:

import json
import datetime

def parse_date(datestr):
    return datetime.datetime.strptime(datestr, '%a %b %m %H:%M:%S %z %Y')

with open(myfilename) as f:
    mydicts = map(json.loads, filter(str.strip, f))
    # This sorts on date value, but leaves them as original str
    # in dict, can convert ahead of time if you want, or not, as you please
    sorteddicts = sorted(mydicts, key=lambda d: parse_date(d['Date'])]

Upvotes: 2

Kamehameha
Kamehameha

Reputation: 5473

You can use dateutil.parser for parsing dates and add the proper key in the sort function.
This works -

In [20]: from dateutil.parser import parse

In [21]: l = [{'Name':'xyz','Date':'Thu Jun 26 13:14:17 +0000 2008'},
{'Name':'xyz','Date':'Thu Jun 19 13:14:17 +0000 2009'},
{'Name':'xyz','Date':'Thu Jun 26 13:15:17 +0000 2008'}]

In [22]: sorted(l, key=lambda x: parse(x['Date']))
Out[22]:
[{'Date': 'Thu Jun 26 13:14:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 26 13:15:17 +0000 2008', 'Name': 'xyz'},
 {'Date': 'Thu Jun 19 13:14:17 +0000 2009', 'Name': 'xyz'}]

Upvotes: 2

Related Questions