2010-09-02 79 views
0

我需要改變的時間戳處於困境日誌文件,因爲其中有一半是不正確的,現在我已經更新了系統時間...變化時間戳

文件中的每一行的格式如下:

04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (10.0.0.1) 

所有時間戳都是8個小時。這是我到目前爲止:

#!/usr/bin/python 
from time import strftime, strptime 

f = open("query.log","r") 
d = f.readlines() 

i = 0 
while not d[i].startswith("20-Aug"): 
    print strftime('%d-%b-%Y %H:%M:%S', strptime(d[i].split(".")[0], '%d-%b-%Y %H:%M:%S')) 
    i+=1 

任何想法,將不勝感激!

回答

0
from datetime import datetime, timedelta 

tfmt = "%d-%b-%Y %H" 
tfmtlen = 14 

def changestamp(line, **kwargs): 
    linetime = datetime.strptime(line[:tfmtlen],tfmt) 
    linetime += timedelta(**kwargs) 

    return linetime.strftime(tfmt) + line[tfmtlen:]  

輸出:

>>> line = "04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.c... 
>>> changestamp(line, hours=8) 
'04-Aug-2010 15:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (... 
>>> changestamp(line, hours=-8) 
'03-Aug-2010 23:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (... 
>>> changestamp(line, weeks=52, days=-365+1/3, hours=24) 
'04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (... 
+0

哇,謝謝!這個解決方案太棒了! – crosswired 2010-09-02 22:28:04