【问题标题】:find timestamp by date_format with regexp使用正则表达式按 date_format 查找时间戳
【发布时间】:2014-12-17 10:29:58
【问题描述】:

我正在考虑一个函数,它能够通过将 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 并将其解析为正则表达式。有没有更好的方法?

【问题讨论】:

    标签: python regex python-2.7


    【解决方案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's 时间戳格式

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

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2018-08-11
      相关资源
      最近更新 更多