(Python) PyProgram #7 - Time Object Diffs
December 14, 2007I had two time objects and needed to find the difference of time between them. Upon Googling, querying in #python and checking the documentation, found that there is not built-in function available for this. Though there were some cookbook recipes, I wanted to write my own solution to find the difference between two datetime.time objects. Though datetime.timedelta was for time difference requirements it only has a days, seconds and microseconds property while I need hour, minute and seconds. Thus, I wrote my timediff method which accepts two time objects btime and stime where btime is a bigger time than stime (b for big and s for small
), and it returns a datetime.time object for the difference time. (Why I need to have time objects? I use storm ORM
)
def timediff(btime, stime):
"""Difference between two datetime.time objects
Accepts two datetime.time objects where btime > stime
Returns a datetime.time object of the difference in time of
the two datetime objects.
"""
btdelta = timedelta(hours=btime.hour, minutes=btime.minute, seconds=btime.second)
stdelta = timedelta(hours=stime.hour, minutes=stime.minute, seconds=stime.second)
tdiff = btdelta - stdelta
tdiffsec = tdiff.seconds
if tdiffsec < 60 and tdiffsec > 0:
return time(0, 0, int(tdiffsec))
elif tdiffsec < 3600 and tdiffsec > 0:
tdiffsplit = str(tdiffsec/60.0).split('.')
tdiffmin = int(tdiffsplit[0])
tdiffsec = float("0."+tdiffsplit[1])*60
return time(0, int(tdiffmin), int(tdiffsec))
elif tdiffsec > 0:
tdiffhourmin = str(tdiffsec/3600.0).split('.')
tdiffhour = int(tdiffhourmin[0])
tdiffminsec = str(float("0."+tdiffhourmin[1])*60).split('.')
tdiffmin = int(tdiffminsec[0])
tdiffsec = float("0."+tdiffminsec[1])*60
return time(tdiffhour, tdiffmin, int(tdiffsec))
else:
return time(0, 0, 0)
Posted by technofreak









