Home > database >  python: can the time library do task: the loop should stop when a certain time passes?
python: can the time library do task: the loop should stop when a certain time passes?

Time:01-27

can the time library help with the task: the loop should stop when a certain time passes? I'm going to write a light game program on PYTHON that should stop after for example 1 minute and output the result

i cant search information about this function

CodePudding user response:

You need to take time at the start and break your loop when the difference between current time and time at the start is more than you want.

import time

start_time = time.time()

while True:
    current_time = time.time()
    if current_time - start_time > 60: #time in seconds
        break
    #your code

You can also add time.sleep(0.01) to the loop to limit your fps.

CodePudding user response:

from datetime import datetime, timedelta

end_time = datetime.now()   timedelta(minutes=1)

while end_time >= datetime.now():
    print("Your code should be here")
  • Related