[Python] I'm very, very curious about how to renew the time in the while True statement.crying

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

from datetime import datetime
import time


now= datetime.now()

while TRUE : 
    try : 
        print(now.minute)
        time.sleep(3)
    except : 
        pass
        time.sleep(3)

This is... I can't update the time.ㅠ<

python

2022-09-20 08:39

2 Answers

now=datetime.now() is outside the while statement, so there seems to be a problem. I'm not sure what exception the try-exception phrase was used for, but I don't think there will be any problem if you write the code like this.

from datetime import datetime
import time


now = datetime.now()

while True: 
    now = datetime.now()
    try : 
        print(now.minute)
        time.sleep(3)
    except : 
        pass
        time.sleep(3)

Of course, it will be updated once every 3 seconds, and the time will be checked for minutes, so if it is renewed 20 times, data number 1 will change.


2022-09-20 08:39

First, datetime.now() is to store the time at which the function is executed, so the first run time outside of the while statement is recorded.

It can be used as below.

from datetime import datetime
import time

start = datetime.now()
# # after some codes...
time.sleep(1)
# ...
end = datetime.now()

print(end-start)

Therefore, the reference object of the now variable must be updated within the while statement to change the time.

Another issue is try-exception, but I don't think there will be any exceptions from the code I wrote.

Therefore, you should study the try-exception or think of another way to do whatever you want.


2022-09-20 08:39

If you have any answers or tips


© 2022 pinfo. All rights reserved.