2016-09-30 27 views
2

我想使用正則表達式更改某些文本行中的時間格式。 如何使用舊時間值? 我的代碼至今:使用正則表達式在文本文件中重新格式化日期時間值

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到16年9月29日16時38分09秒。

回答

1

您可以在您的正則表達式中添加更多捕獲組,並使用具有相應反向引用的替換模式。

使用

r'(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}' 
    |- 1-| |- 2-| |-3 -| | ----- 4 ---- | 

r'\1.\2.\3 \4'取代。

查看regex demo

注意:如果有更長的子字符串看起來像這些日期時間戳,則可能需要將整個模式用字邊界\br'\b(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}\b'括起來。