如何从python3的日志文件中获取最新的时间戳。日志文件可以以mb为单位,有时以gb为单位。
eg : The format is 2017-02-13 17:58:38
2017-02-13 20:07:17 [HTTP-9] DEBUG
2017-02-17 20:07:18 [HTTP-9] DEBUG
2017-02-20 20:07:18 [HTTP-9] DEBUG
.
.发布于 2017-02-23 02:52:38
一种方法是使用最大大小为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]或者如果您想要转换为time object或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()https://stackoverflow.com/questions/42399778
复制相似问题