2017-02-22 50 views
2

如何從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 
. 
. 
+0

它看起來像你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出以及實際獲得的輸出(輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/questions/how-to-ask)。 – TigerhawkT3

+2

我投票結束這個問題作爲題外話,因爲SO不是一個編碼服務。 – TigerhawkT3

+2

從你顯示的文件部分,你所需要的只是最後一行,你可以用一個簡單的'tail -1 filename.txt'來獲得。 – TigerhawkT3

回答

0

的方法之一是爲了得到最後一行,然後使用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() 
+0

但我們是否使用上述代碼獲得最新的時間戳? – skyrocker

+0

@skyrocker它會給你最後一行,然後你可以簡單地使用'str.split()' – Kasramvd

+0

集合提取該行的時間--deque在我嘗試時會拋出一個錯誤。 last_line = d(f).pop() TypeError:'collections.deque'對象不可調用 – skyrocker