Sam
Sam

Reputation: 53

How to print remaining time in time sleep in python?

there is sample of code

 print ("run some code  line here")
 time.sleep(100) # print remaining time for example 35 sec left

I want to try print the remaining time live or after (x sec ) of sleep time

there is any way to do this ? it's possible

Upvotes: 0

Views: 1171

Answers (2)

Amir Shamsi
Amir Shamsi

Reputation: 361

use this function:

import time
def time_left(sleep_time, step=1):
    for _ in range(sleep_time, 0, (-1)*step):
        print('\r{} sec left'.format(_), end='')
        time.sleep(step)

sleep_time is the time you expect to set the sleep and step is for the step you want to go forward and the default is 1sec

and finally, use it in your loop:

for i in range (5):
    print (i)
    time_left(100)

Upvotes: 0

maya
maya

Reputation: 1080

try this:

import time


def sleep(num):
    for i in range(num):
        print("\rTime remaining: {} seconds.".format(num - i), end='')
        time.sleep(1)


sleep(100)

Upvotes: 1

Related Questions