Search code examples
pythonlinepython-mode

How can I calculate time correctly?


*Here is my code * I want get ühole number

from time import time
import math
start=time()
total_time= 30
while time!=0:
    move=input('Chess move:')
    if move !='off':
     print(start)
     remaining_time=math.floor(total_time-start)
     print('Remaninig time:',remaining_time)
    else:
        end=time()
        break

Here is result

Chess move:
>>> f2-f4
1667907784.8287
Remaninig time: -1667907755
Chess move:
>>> off

But I want result like this:

enter image description here


Solution

  • time.time() returns seconds since Jan 1 1970. So 30-1667908542 is a negative number. What you want to do is calculate the elapsed time and subtracting that from your time limit.

    from time import time
    import math
    start=time()
    max_time= 30
    remaining_time = max_time
    while remaining_time>0:
        move=input('Chess move:')
        if move !='off':
            print(start)
            time_elapsed=math.floor(time()-start)
            remaining_time=max_time-time_elapsed
            print('Remaninig time:',remaining_time)
    

    When the loop exits the time is over.