Luiza
Luiza

Reputation: 7

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

Upvotes: 0

Views: 37

Answers (2)

Domi
Domi

Reputation: 143

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.

Upvotes: 0

mlokos
mlokos

Reputation: 409

Python time.time() returns time since January 1, 1970. Not since start of the program

It is better to compare difference between current time and start_time

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(time()-start)
     print('Remaninig time:',remaining_time)
    else:
        end=time()
        break

Upvotes: 0

Related Questions