代码之家  ›  专栏  ›  技术社区  ›  Kade Williams

从行中提取datetime.now格式的方法?

  •  1
  • Kade Williams  · 技术社区  · 7 年前

    我有一个日志文件,其中包含

    ### 192.168.70.10 on 2018-06-19 23:57:37.846200 ###
    
    ### 192.168.70.11 on 2018-06-19 23:50:33.073267 ###
    

    我想打印所有以####开头的行,并提取它们的日期/时间,以便与其他日期/时间进行比较。

    我该怎么做?我应该用正则表达式吗?

    这是我正在做的一个例子。。。

    try:
        with open('myfile.log', 'r') as myfile:
            for line in myfile:
                if "###" in line:
                    x = line
    
                print(x)
                # get date and time from x
    
        myfile.close
    except OSError as e:
        print (e)
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   Daniel Lee    7 年前

    您可以使用regex并使用datetime.striptime解析捕获的组

    from datetime import datetime
    import re
    
    with open('myfile.log') as myfile:
        for line in myfile:
            # Adding the ### into the regex allows you to remove the conditional if ### in line
            regex = r'###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###'
            r = re.match(regex, line)
            if r:  # If there is a matching group, return matching group 1
                dt = datetime.striptime(r.group(1), "%Y-%m-%d %H:%M:%S.%f")
    
            print(dt)
    
        2
  •  1
  •   Somil    7 年前

    在这类问题中可以使用regex

    try:
      with open('myfile.log', 'r') as myfile:
        reg = re.compile('^###.*on\s([\w\s.:-]*)')
        for line in myfile:
           m = reg.match(line)
           if m:
             datetime.striptime(m.group(1), "%Y-%m-%d %H:%M:%S.%f")
    
        3
  •  0
  •   Jens Kirk Roybal    7 年前

    假设一条线 如果是固定格式,那么应该可以:

    # Extract the date and time substring.
    s = x[-30:-4]
    
    # Parse the string into a datetime object.
    dt = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")
    

    看到了吗 strptime() documentation

    如果日志文件中某行的格式不同,则 regex 可能有用(参见 Daniel’s answer parsing 一根绳子。