Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在文本文件中使用正则表达式重新格式化日期时间值_Python_Regex_Datetime_Reformatting - Fatal编程技术网

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 ---- |