Python 在文本文件中使用正则表达式重新格式化日期时间值
我想使用正则表达式更改某些文本行中的时间格式。 如何使用旧的时间值? 我的代码到现在为止:Python 在文本文件中使用正则表达式重新格式化日期时间值,python,regex,datetime,reformatting,Python,Regex,Datetime,Reformatting,我想使用正则表达式更改某些文本行中的时间格式。 如何使用旧的时间值? 我的代码到现在为止: def file_replace_words(file_in, word_to_replace, replace_with): f = open(file_in, "r+") data = f.readlines() f.seek(0) for line in data: line = re.sub(word_to_replace, replace_with
def file_replace_words(file_in, word_to_replace, replace_with):
f = open(file_in, "r+")
data = f.readlines()
f.seek(0)
for line in data:
line = re.sub(word_to_replace, replace_with, line)
f.write(line)
f.truncate()
f.close()
f.file_replace_words(path_putty_log, r"(\d\d\/\d\d\/\d\d) - \d\d:\d\d:\d\d:\d\d\d",
"my time in format 31.12.1999 11:54:23")
我想将值从29/09/16-16:38:09:808更改为29.09.16 16:38:09。您可以在正则表达式中添加更多捕获组,并使用具有相应反向引用的替换模式 使用 并替换为
r'\1.\2.\3\4'
看
注意:如果有较长的子字符串看起来像这些日期戳,您可能希望用单词边界将整个图案括起来\b
:r'\b(\d\d)/(\d\d)/(\d\d)-(\d\d:\d\d:\d\d\d):\d{3}\b'
r'(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}'
|- 1-| |- 2-| |-3 -| | ----- 4 ---- |