使用Python搜索/替换文件中的日期/时间

时间:2013-11-08 20:10:07

标签: python logging

我正在构建一个测试环境,无论何时运行测试,都需要将日志滚动到该测试环境。基本上,这意味着如果日志最初来自[2010-05-16 13:45:23],我们需要更新年 - 月 - 日期,并反映当时和现在()之间的时间差异。接下来,时间都是不同的,需要维持他们的顺序,以便项目#10比项目#200旧。

我已经尝试在python和line.replace中使用re模块。

import re
from datetime import date


##  Defines time variables
curyr = str(date.today().year)

##Declaring input/output files
inputfile = open('datetest.log', 'r')
outputfile = open('new_dtest.log', 'w')

for line in inputfile:
        outputfile.write(line.replace('2009', curyr))
##  Just trying to replace the year with the following:
##      outputfile.write(re.sub(r'\d\d\d\d', curyr, curyr)

##  Closing files
inputfile.close()
outputfile.close()

正如你所看到的,我并没有抓住我可以通过哪个模块实现这个目标。非常感谢任何帮助。

文件'datetest.log'只需加载两个测试条目:

[2010-05-16 13:45:23]
[2011-06-17 14:55:33]

1 个答案:

答案 0 :(得分:0)

如果我理解你正确的要求,我会在“datetime space”中构建你的新日志日期,然后在你写出来之前将它们转换成字符串,例如。

For datetest.log with:
2011-06-17 14:55:33
2011-06-17 13:55:33
2011-06-17 12:55:33
2011-06-17 10:55:33
2011-06-17 07:55:33
2011-06-17 04:55:33
2011-06-17 01:55:33
====================

from datetime import datetime as dt
from datetime import timedelta as td

with open("datetest.log") as f:
    old = f.readlines()

sin = dt.strptime
sout = dt.strftime

# Convert your string data into datetime objects
format = "%Y-%m-%d %H:%M:%S"
old_dt = [ sin(t.strip(), format) for t in old if t.strip() ]
# Get the time differences between your old date tags
old_diffs = [td(0.0)]
for i in range(1, len(old_dt) - 1):
    old_diffs.append( ( old_dt[i]- old_dt[i+1] ) + old_diffs[i-1])

# Use the current date as your new starting point, 
# and subtract off the old time diffs    
current_dt = dt.now()
new_dt = [ (current_dt - t) for t in old_diffs ]

# Convert back into strings for writing out
new = [sout(t, format) for t in new_dt]

new
['2013-11-08 14:19:02',
 '2013-11-08 13:19:02',
 '2013-11-08 11:19:02',
 '2013-11-08 08:19:02',
 '2013-11-08 05:19:02',
 '2013-11-08 02:19:02']

您现在可以将new写为新的日志文件。