如何从python3中的日志文件中获取最新的时间戳。日志文件可以是mb,有时也可以是gb&#39。
<build>
<finalName>Test</finalName>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/test/resources</directory>
</resource>
</resources>
</build>
答案 0 :(得分:0)
一种方法是使用最大值为1的collections.deque
以获取最后一行,然后使用str.split()
方法来提取时间:
from collections import deque
with open(file_name) as f:
last_line = deque(f, maxlen=1).pop()
您还可以使用itertools.dropwhile()
来删除文件对象(这是一个类似迭代器的对象)的行,直到它们满足某些条件,例如基于行的末尾。
from itertools import dropwhile
with open(file_name) as f:
last_line = next(dropwhile(lambda x: not x.endswith('G'), f))
# note that in aforementioned function supposed that all the lines ends with G (apparently, but all except the last line ends with newline)
在这两种方法中,你都可以得到以下时间:
time_string = last_line.rsplit(' ', 2)[0]
或者,如果您想转换为时间对象,或timestamp
:
from datetime import datetime
datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')
datetime.strptime(a, '%Y-%m-%d %H:%M:%S').timestamp()