使用正则表达式按日期格式查找时间戳

时间:2014-12-17 10:29:59

标签: python regex python-2.7

我正在考虑一个函数,它能够通过将DATEFORMAT作为参数传递来在日志文件中找到时间戳,如:

def find_some_dates(logfile, timestamp_format='%d/%b/%Y %H:%M:%S.%f'):
    # find timestamps by timestamp_format
    # pass it to datetime.strptime
    # return unix timestamp

时间戳可以是一行内的任何位置。 E.g。

[1] 17/Dec/2014 15:00:21.777 something happened
On 17/Dec/2014 15:00:21.777 something happened
17/Dec/2014 15:00:21.777 - something happened

我正在考虑某种映射,它采用timestamp_format并将其解析为regexp。有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

好吧,这就是我想出的。 假设在日志文件时间戳之前没有其他文本,我可以使用此

from datetime import datetime

line = "17/Dec/2014 15:00:21.777 something happened right here"

def find_some_dates(log_line, timestamp_format='%d/%b/%Y %H:%M:%S.%f'):
    try:
        date_str = datetime.strptime(log_line, timestamp_format)
    except ValueError as val: 
        print val.args[0].split(':').pop()

    # get substr with logfile timestamp and rerun the whole thing to convert to unix timestamp

find_some_dates(line)

因为事实并非如此,我编写了一个解析器,它遍历给定的映射和re.sub的 TIMESTAMP_FORMAT

format_mapping = {('%a', '%A', '%B', '%b'): '[a-zA-Z]+',
                  ('%d', '%m', '%w', '%H', '%y', '%f', '%M', '%I', '%S', '%U', '%j'): '[0-9]+',
                   '%Z': '[A-Z]+'}