How can I format the time elapsed from seconds to hours, mins, seconds?
My code:
start = time.time()
... do something
elapsed = (time.time() - start)
Actual Output:
0.232999801636
Desired/Expected output:
00:00:00.23
import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))
You could exploit timedelta
:
>>> from datetime import timedelta
>>> str(timedelta(seconds=elapsed))
'0:00:00.233000'
The strftime
function of time
itself can be (ab)used with limitations (no millisec and <24 hr)
elapsed = 4*3600 + 13*60 + 6 # 15186 s
time.strftime("%Hh%Mm%Ss", time.gmtime(elapsed)) # '04h13m06s'
If you want one line of code without import any other library, that worked for me (Python v3.7.11):
print("Elapsed time: " + time.strftime("%H:%M:%S.{}".format(str(elapsed % 1)[2:])[:15], time.gmtime(elapsed)))
Output:
Elapsed time: 00:38:01.357318
You can control the milliseconds to be displayed by modifying "[:15]" to "[:11]", then you will get the desired result:
Elapsed time: 00:45:18.65
Perhaps, It would be useful for someone. I have written the function below, which is deriving a string like '2w', '1y' and etc from a number of seconds:
def format_seconds_to_duration(seconds):
df = pd.DataFrame(
[
{ 'Metric': 'y', 'Duration' : seconds / (365*24*60*60)},
{ 'Metric': 'mo', 'Duration' : seconds / (30*24*60*60)},
{ 'Metric': 'w', 'Duration' : seconds / (7*24*60*60)},
{ 'Metric': 'd', 'Duration' : seconds / (24*60*60)},
{ 'Metric': 'h', 'Duration' : seconds / (60*60)},
{ 'Metric': 'm', 'Duration' : seconds / (60)},
{ 'Metric': 's', 'Duration' : seconds}
],
columns=['Metric', 'Duration']
)
res = df[ df['Duration'].round() > 0 ].head(1)
return str(round(res['Duration'].iloc[0])) + res['Metric'].iloc[0]
If you want to include times like
0.232999801636
as in your input:Example: