Search code examples
pythonregexfilepython-datetime

Add 5 seconds to all timestamps in a text file


I have a text file that contains information that looks like this:

341
00:33:17,72 --> 00:33:24,05
this happen because si se puede
yes we can. Thank you very much.

I'm trying to find all instances of time and add five seconds to the time. This is what I have so far:

import re
import string
from datetime import datetime, timedelta
import fileinput



fr = open('project.txt')
text = fr.read()
fr.close()
regex = r"(\d+):(\d+):(\d+),(\d+)"
matches = re.finditer(regex, text, re.MULTILINE)

def changeTimes():
    for matchNum, match in enumerate(matches, start=1):

        print("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum=matchNum, start=match.start(),
                                                                            end=match.end(), match=match.group()))
        t1 = datetime.strptime(match.group(), "%H:%M:%S,%f")  # put your time instead
        delta = timedelta(seconds=5)  # seconds, minutes, hours, whatever
        t1 += delta
        print(t1.strftime("%H:%M:%S,%f")[:-4])
        with fileinput.FileInput('project.txt', inplace=True, backup='.bak') as file:
            for line in file:
                print(line.replace(r"(\d+):(\d+):(\d+),(\d+)", t1.strftime("%H:%M:%S,%f")[:-4]), end='')

I am calling changeTimes() below a slew of comments.

I am getting no errors, and also no change to the text file. Why is this?


Solution

  • Assuming your times are fixed formatting, use (\b(?:\d\d:){2}\d\d,\d\d\b) and keep your fileinput.FileInput with inplace=True (there's no need to pattern match on a separate file read--you can do it all in one loop). Provide re.sub with a lambda function that parses, increments and re-formats the matched time strings for each line.

    import fileinput
    import re
    from datetime import datetime, timedelta
    
    def add_seconds(x, fmt="%H:%M:%S,%f", seconds=5):
        return (datetime.strptime(x, fmt) +
                timedelta(seconds=seconds)).strftime(fmt)
    
    pattern = r"(\b(?:\d\d:){2}\d\d,\d\d\b)"
    replacement = lambda x: add_seconds(x.group(0))[:11]
    
    with fileinput.FileInput("project.txt", inplace=True, backup=".bak") as f:
        for line in f:
            print(re.sub(pattern, replacement, line), end="")
    

    Output:

    341
    00:33:22,72 --> 00:33:29,05
    this happen because si se puede
    yes we can. Thank you very much.