简体   繁体   English

python:使用datetime作为关键字对字典进行排序

[英]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”作为键的字典中。

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. 您出错的原因是strptime返回struct_time。 Converting it to UNIX timestamp (which will be a float) should allow you to sort more easily. 将其转换为UNIX时间戳(将是浮点型)应该可以使您更轻松地进行排序。

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. 它将自动在每个元组的第一个条目上排序,该条目应为日期时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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