Calculate elapsed time for timestamps in (log)file


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. """Calculate elapsed time for timestamps in logfile.
  3.  
  4. Syntax: time_elapsed.py <filename> <first-line-number> <last-line-number>"""
  5.  
  6. import sys, linecache
  7. from time import mktime, strftime, strptime, gmtime
  8.  
  9. filename, first_line, last_line = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
  10.  
  11. print "Lines for the given range (%d-%d) in file (%s):" % (first_line, last_line, filename)
  12. print "-" * 70
  13. for line in range(first_line, last_line+1):
  14. print linecache.getline(filename, line).strip()
  15.  
  16.  
  17. # The first 16 characters in each line of the file are the timestamp.
  18. # Modify this for your needs.
  19. begin_time = linecache.getline(filename, first_line).strip()[0:15]
  20. end_time = linecache.getline(filename, last_line).strip()[0:15]
  21.  
  22. # Use this code if the logfile has a delimiter which seperates fields.
  23. # In this example ";":
  24. #begin_time = linecache.getline(filename, first_line).split(";")[0]
  25. #end_time = linecache.getline(filename, last_line).split(";")[0]
  26.  
  27.  
  28. # Format strings: http://docs.python.org/library/time.html#time.strftime
  29. elapsed_sec = mktime(strptime(end_time, "%b %d %H:%M:%S")) - mktime(strptime(begin_time, "%b %d %H:%M:%S"))
  30. elapsed_readable = strftime("%H:%M:%S", gmtime(elapsed_sec))
  31.  
  32. print "-" * 70
  33. print "Elapsed time (seconds) :", elapsed_sec
  34. print "Elapsed time (HH:MM:SS):", elapsed_readable

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.