This is a question related to Python time

Asked 2 years ago, Updated 2 years ago, 74 views

import time

start_time = time.time() #time.time()-start_time is the total running time of the program
count = 0

while True:

   if A<10 and B<10

        ~~~~~~

   if A>20 and B>20

        break

It's a rough structure of the code I made

If you run file, the values of A and B will continue to change from then.

A<10 and B<10 do not cause a situation below the first if.

The conditions of A<10 and B<10 must last for more than 3 seconds so that the situation below if occurs.

I tried it in two ways

if A<10 and B<10

  temp = time.time() - start.time #puts the time of the moment when the condition is satisfied into the temporary variable temp

     If time.time()-start.time-temp>=3#If the time after the condition is satisfied is more than 3,

        ~~~~~~~~~~~~~~ #Run

The above method failed because the value of time.time()-start.time in the while statement could not be fixed because the value of temp kept changing.

The second method is

if A>=10 and B>=10 #Unless the execution conditions
     time.time()-start.time=0 #Initialize the run time to 0

If A<10 and B<10 #If the execution conditions are met, 
     If time.time()-start.time>=3 #And after more than 3 seconds,
         ~~~~~~ #Run

SyntaxError: can't assign to operator.

You can assign the value of time.time()-start.time to a variable, but vice versa, such an error appears.

I doubt that we can solve it by using time now, so please give me some advice...

python anaconda

2022-09-22 12:50

1 Answers

You want the conditions to last more than 3 seconds to make sure the back code is executed, right? (I guessed it in the comments))

I don't think we can avoid busy-waiting... How about this code?

from datetime import datetime

before = datetime.now()
while(True):
    if A < 10 and B < 10:
        now = datetime.now()
        if (now - before).seconds <= 180: # A < 10 and B < 10 Continue to check if it lasts for 3 minutes
            continue
    else:
        Before = datetime.now() # Initialize time count if not A < 10 and B < 10

    if A > 20 and B > 20:
        pass
        # blah blah blah blah


2022-09-22 12:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.