简体   繁体   中英

python : sorting a dictionary using datetime as key

I am trying to read from a log file which has a timestamp with milliseconds as follows and then inserting into a dictionary based on 'st_time' as key.

st_time = datetime.strptime(t_str[0],"%d/%b/%Y %H:%M:%S.%f")
final_dict[st_time] = line
for key in sorted(final_dict.iterkeys()):
    print "%s : %s" %(key,final_dict[key])

But I get this error below

for key in sorted(final.iterkeys()):


TypeError: can't compare datetime.datetime to tuple

Sample: An entry from log file

Jul  1 03:27:12 syslog: [m_java]**[ 1/Jul/2013 03:27:12.818]**[j:[SessionThread <]^Iat com/avc/abc/magr/service/find.something(abc/1235/locator/abc;Ljava/lang/String;)Labc/abc/abcd/abcd;(bytecode:7)

t_str[0] --> ['29/Jun/2013 01:16:06.149']

st_time --> 2013-06-29 01:16:06.149000

Thanks for any help!

st_time = datetime.strptime(t_str[0],"%d/%b/%Y %H:%M:%S.%f")
key = float(time.mktime(st_time.timetuple()) + st_time.microsecond / 1000000.0)
final_dict[key] = line
for key in sorted(final_dict.iterkeys()):
    print "%s : %s" %(key,final_dict[key])

The reason for your error is strptime returns a struct_time. Converting it to UNIX timestamp (which will be a float) should allow you to sort more easily.

If you're using a dictionary and hoping that it will be sorted in any manner, then you're using the wrong datatype.

There are many other sub-types of dictionary, that do support sorting, but I would recommend using a two-element tuple instead.

sorted_times = sorted([(k, v) for k, v in final_dict.items()])

It will automatically sort on the first entry of each tuple, which should be the datetime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM