如何從python3中的日誌文件獲取最新的時間戳。日誌文件可以是MB,有時也可以是GB。在Python中獲取最新的時間戳
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
.
.
如何從python3中的日誌文件獲取最新的時間戳。日誌文件可以是MB,有時也可以是GB。在Python中獲取最新的時間戳
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
.
.
的方法之一是爲了得到最後一行,然後使用str.split()
方法,以提取一次使用,最大尺寸1 collections.deque
:
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()
它看起來像你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出以及實際獲得的輸出(輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/questions/how-to-ask)。 – TigerhawkT3
我投票結束這個問題作爲題外話,因爲SO不是一個編碼服務。 – TigerhawkT3
從你顯示的文件部分,你所需要的只是最後一行,你可以用一個簡單的'tail -1 filename.txt'來獲得。 – TigerhawkT3