1

我正在构建一个测试环境,该环境需要在运行测试时将其日志滚动到。基本上,这意味着如果日志最初来自 [2010-05-16 13:45:23],我们需要更新 Year-Month-Date 并反映 then 和 now() 之间的时间差异。接下来,时间都不同了,需要保持它们的顺序,以便项目#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]
4

1 回答 1

0

如果我理解您的要求正确,我会在“日期时间空间”中构建您的新日志日期,然后在您写出之前将它们转换为字符串,例如

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新的日志文件。

于 2013-11-08T22:20:37.540 回答