-2

How can I calculates the elapsed time between a start time and an end time of a event using python, in format like 00:00:00 and 23:59:59?

Zulu
  • 8,765
  • 9
  • 49
  • 56

2 Answers2

0

I am not sure how you can do it with time module , but you can use the datetime module for that, get the result datetime.datetime.now() when the event starts and save it in a variable.

Then when the event ends again get datetime.datetime.now() and subtract the first time from it. You will get a datetime.timedelta() object, which you can convert to str() to get the data in your required format.

Example/Demo -

>>> d = datetime.datetime.now()
>>> d1 = datetime.datetime.now()
>>> str(d1 - d)
'0:00:06.989000'
>>> str(datetime.timedelta(0,84332,12332))
'23:25:32.012332'

If you do not want the microsecond part, you can just use rsplit() on '.' and take the first part, Example -

>>> str(d1 - d).rsplit('.',1)[0]
'0:00:06'
>>> str(datetime.timedelta(0,84332,12332)).rsplit('.',1)[0]
'23:25:32'
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

time.time() is just system time, nothing more. datetime is probably a plan, but if you want to DIY, divmod works pretty well

def pretty_time(t):
    """takes a time, in seconds, and formats it for display"""
    m, s = divmod(t, 60)
    h, m = divmod(m, 60)
    s = round(s) #Rounds seconds to the nearest whole number
    h = str(h).rjust(2,'0') #covert to strings,
    m = str(m).rjust(2,'0') #adding 0 if necessary to make 
    s = str(s).rjust(2,'0') #each one two digits long
    return "{}:{}:{}".format(h,m,s)

and then just call with

pretty_time(end_time-start_time)

(examples:

In [5]: pretty_time(3600)
Out[5]: '01:00:00'

In [6]: pretty_time(3500)
Out[6]: '00:58:20'

)

(note that I didn't bother to check for times over 24 hours, that'll just give you things like "25:45:21")

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37