Skip to content

Instantly share code, notes, and snippets.

@4s7r0
Created April 4, 2012 06:35
Show Gist options
  • Save 4s7r0/2299150 to your computer and use it in GitHub Desktop.
Save 4s7r0/2299150 to your computer and use it in GitHub Desktop.
DiffSec - Python - Difference in seconds between two datetime formated strings
import sys,time,string,getopt
def usage():
print "Usage: diffsec.py -f <fromTime> -t <toTime> \n"
sys.exit(2)
def parse_args():
global fromTime,toTime
fromTime = toTime = ""
try:
opts, args = getopt.getopt(sys.argv[1:], "f:t:", ["fromtime", "totime"])
except getopt.GetoptError:
print "Invalid arguments, exiting"
sys.exit(2)
for arg, val in opts:
if arg in ("-f","--fromtime"):
fromTime = val
elif arg in ("-t","--totime"):
toTime = val
if fromTime == toTime == "" :
usage()
def compute_time(time1):
t = time1.split(':')
return time.mktime(time.strptime(":".join(t[0:len(t)]),"%b/%d/%Y %H:%M:%S"))
def subtract(list):
return list[1] - list[0]
def time_convert(secs):
secs = int(secs)
mins = secs // 60
hrs = mins // 60
return "%02d:%02d:%02d" % (hrs, mins % 60, secs % 60)
def main():
parse_args()
print "From time : " + str(fromTime) + '\n' + "To time : " + str(toTime)
timelist = [ fromTime, toTime ]
s = map(compute_time,timelist)
d = subtract(s)
print "diff in seconds : " + str(d)
f = str(d).split('.')
final = time_convert(f[0])
print "Total difference in required format : " + str(final)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment