首页 > 解决方案 > 一种从行中提取 datetime.now 格式的方法?

问题描述

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

### 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)

标签: python

解决方案


您可以在此类问题中使用正则表达式

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")

推荐阅读