-
Notifications
You must be signed in to change notification settings - Fork 10
/
wtimediff
executable file
·78 lines (71 loc) · 2.36 KB
/
wtimediff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# wtimediff (part of ossobv/vcutil) // wdoekes/2015 // Public Domain
#
# Reads log files from stdin and outputs the time difference between
# consecutive lines.
#
# Usage:
#
# $ wtimediff < logfile
# (outputs log lines preceded by the time offset since the previous line)
#
# Example:
#
# $ printf 'abc 12:12:12.12\n18:18:18 foo\n0:00:00.666666 bar\n' |
# wtimediff
#
# Output:
#
# > 0.0 abc 12:12:12.12
# > +21965.88 18:18:18 foo
# > +20502.666666 0:00:00.666666 bar
#
# Limitations:
#
# * Matches time strings [H]H:MM:SS[.sss...] only and ignores date
# strings completely.
# * Alternatively, matches unixtime (1650218400), if only that is
# found on the line.
#
from datetime import datetime, timedelta
import re
import sys
# Match the first occurrence of H:MM:SS.sss...
time_re = re.compile(r'(?:^|.*?[^\d])(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))?')
unixtime_re = re.compile(r'(?:^|.*?[^\d])([1-9][0-9]{9})(?:$|[^\d])')
prevtime = None
for line in sys.stdin:
match = time_re.match(line)
try:
if match:
hour, min_, sec, usec = match.groups()
hour, min_, sec = int(hour), int(min_), int(sec)
usec = int(('%s000000' % (usec or 0,))[0:6])
if prevtime:
curtime = datetime(
prevtime.year, prevtime.month, prevtime.day,
hour, min_, sec, usec)
if curtime < prevtime:
curtime += timedelta(days=1)
assert (curtime - prevtime).days == 0
else:
# May fail for bad times with ValuError.
curtime = datetime(1970, 1, 1, hour, min_, sec, usec)
else:
match = unixtime_re.match(line)
if match:
curtime = datetime.fromtimestamp(int(match.groups()[0]))
else:
raise ValueError('No time found')
if not prevtime:
diff = '0.0' + (' ' * 5)
else:
td = (curtime - prevtime)
diff = '%+6d.%-6s' % ( # 1+5+1+6=13
td.seconds,
('%06d' % (td.microseconds,)).rstrip('0') or '0')
prevtime = curtime
sys.stdout.write(' %13s %s' % (diff, line))
except ValueError: # from datetime()
sys.stderr.write('(skipped: %s)\n' % (line.strip(),))
# vim: set ts=8 sw=4 sts=4 et ai: