Skip to main content
 首页 » 编程设计

python之使用正则表达式按 date_format 查找时间戳

2025年05月04日22kevingrace

我正在考虑一个函数,它能够通过将 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 

时间戳可以在一行中的任何位置。例如

[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 并将其解析为正则表达式。有更好的方法吗?

请您参考如下方法:

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

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 的 时间戳格式

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]+'}