Skip to content

Instantly share code, notes, and snippets.

Last active July 14, 2016 16:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Python: Get time delta from log with YYYY-MM-DD hh:mm:ss format
#!/usr/bin/env python
import sys
from datetime import datetime
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('logfile', help='Log file')
parser.add_argument('-s', '--seconds', default=1, type=int,
help='Only log entries that took over n seconds')
args = parser.parse_args()
with open(args.logfile, 'r') as logf:
log = logf.readlines()
lasttime = None
for line in log:
datestr, timestr = line.split()[0], line.split()[1]
datetimestr = '{} {}'.format(datestr, timestr)
timeobj = datetime.strptime(datetimestr, '%Y-%m-%d %H:%M:%S')
if lasttime:
delta = timeobj - lasttime
if delta.seconds > args.seconds:
print '{}s {}'.format(delta.seconds, lastline)
lasttime = timeobj
lastline = line.strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment