Reformat datetime value with regex in a textfile
<p>I want to change the time format in some text lines with using regex.
How can I use the old time values?
My code until now:</p>

<pre><code>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")
</code></pre>

<p>I want to change the values from 29/09/16 - 16:38:09:808 to 29.09.16 16:38:09.</p>

<p>You may add some more capturing groups into your regex, and use a replacement pattern with corresponding backreferences.</p>

<p>Use</p>

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

<p>and replace with <code>r'\1.\2.\3 \4'</code>.</p>

<p>See the <a href="https://regex101.com/r/QUQ5jN/1" rel="nofollow">regex demo</a>.</p>

<p>NOTE: If there are longer substrings that look like these datetime stamps, you might want to enclose the whole pattern with word boundaries <code>\b</code>: <code>r'\b(\d\d)/(\d\d)/(\d\d) - (\d\d:\d\d:\d\d):\d{3}\b'</code>.</p>

python regex datetime reformatting