2

次のようにミリ秒のタイムスタンプを持つログ ファイルから読み取り、「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])

しかし、私は以下のこのエラーを受け取ります

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


TypeError: can't compare datetime.datetime to tuple

サンプル: ログ ファイルからのエントリ

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

助けてくれてありがとう!

4

2 に答える 2

-1

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.

于 2013-07-05T17:37:52.090 に答える