Question

I was wondering how I would make my time in Python 3.3 display in minutes and seconds. At the minute, it only displays in seconds? Many Thanks.

start_time=time.time()

# program operation

end_time=time.time()-start_time
print(end_time)
Was it helpful?

Solution

You can use the datetime module

import datetime
end_time = 400 # this is the difference in your example, in seconds

str(datetime.timedelta(seconds = end_time))

Result

'0:06:40'

OTHER TIPS

Use the datetime module. Some people use the time module with sleep() function, but it is inaccurate. By the level of you're experience with this, you should use time module.

import time
seconds = 0
minutes = 0
while True:
    print('\r'f'{minutes}:{seconds}', end='')
    time.sleep(1)
    seconds += 1
    if seconds == 60:
        minutes += 1
        seconds = 0
    elif minutes == 2:
        break*

The '\r' in print statement is to take the printing cursor in the terminal to the start of the line. Python by default adds a new line character(\n, the cursor goes to the next line.) to a string and therefore, set the 'end = none' for the string.

you can use time module :

import time
def initial_input():
    global error
    global hours
    global minutes 
    global seconds
    error = 0
    hours = input("How much hours ? : ")
    minutes = input("How much minutes ? : ")
    seconds = input("How much seconds ? : ")
    try:
        hours,minutes,seconds = int(hours),int(minutes),int(seconds)
    except:
        print("input no ok")
        error = 1
        initial_input()
    if hours > 99 or minutes > 60 or seconds > 60:
        print("Error please input correct numbers")
        initial_input()
        error = 1
error = 0
initial_input()
if error == 0:
    max_range = hours*3600 + minutes * 60 + seconds
    end_range = 0
    while end_range <= max_range -1:
        if minutes <= 0 and seconds <= 0:
            hours -= 1
            minutes = 60
        if seconds <= 0:
            minutes -=1
            seconds = 59
        else:
            seconds -=1
        print(f"\rThere is {hours} hours, {minutes} minutes, {seconds} seconds 
left !",end="")
        max_range -= 1
        time.sleep(1)
    print("\nNo time left ! ")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top