更改绑定日志文件中的时间戳

时间:2010-09-02 21:32:23

标签: python timestamp bind

我需要更改绑定日志文件中的时间戳,因为现在我已经更新了系统时间,其中一半是不正确的......

文件中的每一行都遵循以下格式:

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

任何想法都会受到赞赏!!

1 个答案:

答案 0 :(得分: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 + (...