python:使用正则表达式从日志文件中读取日期时间

时间:2013-07-05 15:38:55

标签: python regex

我有一个日志文件,其文本看起来像这样。

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_pat = re.compile(r".*\[\d+/\D+/.*\]")

我想查看文件中的每一行,能够应用此模式并根据日期和时间对行进行排序。时间。

有人可以帮我这个吗?谢谢!

3 个答案:

答案 0 :(得分:2)

您的空间需要添加到正则表达式

text = "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)"
matches = re.findall(r"\[\s*(\d+/\D+/.*?)\]", text)
print matches
['1/Jul/2013 03:27:12.818']

接下来使用以下函数解析时间

http://docs.python.org/2/library/time.html#time.strptime

最后使用它作为dict的键,并将行作为值,并根据键对这些条目进行排序。

答案 1 :(得分:1)

你不匹配初始空间;您还希望将日期分组以便轻松提取,并将\D.*模式限制为非贪婪:

t_pat = re.compile(r".*\[\s?(\d+/\D+?/.*?)\]")

演示:

>>> re.compile(r".*\[\s?(\d+/\D+?/.*?)\]").search(line).group(1)
'1/Jul/2013 03:27:12.818'

你可以更多地缩小模式;你只需要匹配月份的3个字母,例如:

t_pat = re.compile(r".*\[\s?(\d{1,2}/[A-Z][a-z]{2}/\d{4} \d{2}:\d{2}:[\d.]{2,})\]")

答案 2 :(得分:1)

Read all the lines of the file并使用sort函数并传入parses out the date并将其用作the key for sorting的函数:

import re
import datetime

def parse_date_from_log_line(line):
    t_pat = re.compile(r".*\[\s?(\d+/\D+?/.*?)\]")
    date_string = t_pat.search(line).group(1)
    format = '%d/%b/%Y %H:%M:%S.%f'
    return datetime.datetime.strptime(date_string, format)

log_path = 'mylog.txt'
with open(log_path) as log_file:
    lines = log_file.readlines()
    lines.sort(key=parse_date_from_log_line)