在文本文件中使用正则表达式重新格式化日期时间值

Reformat datetime value with regex in a textfile

我想使用正则表达式更改某些文本行中的时间格式。 如何使用旧时间值? 到目前为止我的代码:

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'(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}'
  |- 1-| |- 2-| |-3 -|   | ----- 4 ---- |

并替换为 r'.. '.

参见regex demo

注意:如果有看起来像这些日期时间戳的较长子字符串,您可能希望用单词边界包围整个模式 \br'\b(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}\b'.