Convert time in seconds to format HH:MM:SSConvert



Sometimes we need to convert a time like this StackOverflow answer where we need to format a time in seconds to Hours:Minutes:Seconds

In this example we have 2 times in seconds firstTime and secondTime

firstTime = 1416248381 
secondTime = 1416248157

duration = firstTime - secondTime

print duration
Output: 224

As we can see, the duration of the time between firstTime and secondTime is 224

To convert this seconds to HH:MM:SS format (Hours:Minutes:Seconds) we can do:

Using datetime

import datetime

firstTime = 1416248381 
secondTime = 1416248157
duration = firstTime - secondTime

print str(datetime.timedelta(seconds=duration))

Output: '0:03:44'

Using time

import time

firstTime = 1416248381 
secondTime = 1416248157
duration = firstTime - secondTime

time.strftime("%H:%M:%S", time.gmtime(duration))

Output: '0:03:44'
You can copy paste the code in your python console to check this out !

Leave a comment

You have to wait to comment again. Wait Time: