• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import sys
2import os
3from datetime import datetime
4
5# Usage:
6# replace_timestamp.py input.txt output.txt timestamp_string
7#
8# Description:
9# Replace timestamp in the input.txt with the difference timestamp to timestamp_string.
10#
11# Example: replace_timestamp.py input.txt output.txt "01-28 18:12:30.339".
12#
13def main():
14    filepath = sys.argv[1]
15    if not os.path.isfile(filepath):
16        print("File path {} does not exist. Exiting...".format(filepath))
17        sys.exit()
18
19    output_filepath = sys.argv[2]
20
21    timestamp_str = sys.argv[3]
22    date_time_obj = datetime.strptime(timestamp_str, '%m-%d %H:%M:%S.%f')
23
24    output_fp = open(output_filepath, 'w')
25    i = 1
26    with open(filepath, 'r', errors = 'ignore') as fp:
27        for line in fp:
28            newline = replace_timestamp_abs(line, timestamp_str, date_time_obj)
29            output_fp.write(newline)
30            i = i + 1
31    fp.close()
32    output_fp.close()
33
34
35def replace_timestamp_abs(line, timestamp_str, date_time_obj0):
36    if line[:5] != timestamp_str[:5]:
37        return line
38
39    index = line.find(" ", 6)
40    if index <= 0:
41        return line
42    substr0 = line[:index]
43    substr1 = line[index:]
44
45    try:
46        date_time_obj = datetime.strptime(substr0, '%m-%d %H:%M:%S.%f')
47    except ValueError:
48        return line
49
50    date_time_delta = date_time_obj - date_time_obj0
51    date_time_delta_str = str(date_time_delta)
52    return date_time_delta_str + substr1
53
54if __name__ == '__main__':
55    main()
56