There are already many articles on how to measure elapsed time using the time module in a Python program, and I learned a lot. I haven't come up with a way to display hours: minutes: seconds like "03:14:15", so I'll write it down.
That said, it just uses the time module to calculate the elapsed time in seconds and convert it to muddy.
import time
# get time when the program stated
start_time = time.time()
"""
Your program here
"""
# calculate elapsed time
elapsed_time = int(time.time() - start_time)
# convert second to hour, minute and seconds
elapsed_hour = elapsed_time // 3600
elapsed_minute = (elapsed_time % 3600) // 60
elapsed_second = (elapsed_time % 3600 % 60)
# print as 00:00:00
print(str(elapsed_hour).zfill(2) + ":" + str(elapsed_minute).zfill(2) + ":" + str(elapsed_second).zfill(2))
Get the current time with time.time ()
.
Do this before and after the program starts and calculate the difference.
Since small numbers such as milliseconds are unnecessary, it is converted to int type.
When the quotient of seconds divided by 3600, Divide the quotient by dividing the remainder by 60, The remainder is seconds, It is said.
I use .zfill ()
to prefix each number with a single digit if it is a single digit.
It seems that .zfill ()
can be used for str type.
In this case, we want to use 2 digits, so we use .zfill (2)
.