0

这个问题非常直截了当。观察下面的代码:

import time, datetime
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " This is a test"
time.sleep(5) # 5 seconds until next statement
print timer + " Test after 5 seconds, so the timer should've changed"

执行代码后的结果:

13:22:07 This is a test
13:22:07 Test after 5 seconds, so the timer should've changed

正如您在结果中看到的,计时器与睡眠相同。如果我们在这里谈论分钟,我会接受它,但代码结果中的秒数保持不变。

我们将如何使用一个在一次执行一条语句后动态变化的计时器?

4

3 回答 3

1

When you assign datetime.datetime.now().strftime('%H:%M:%S') to timer variable current time assign to timer variable.

So after 5 second just reassign timer variable with current time[5 second later]
Try This One

import time, datetime
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " This is a test"
time.sleep(5) # 5 seconds until next statement
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " Test after 5 seconds, so the timer should've changed"
于 2013-10-01T10:27:01.530 回答
0

Don't use the timer again. Instead use datetime.datetime.now().strftime('%H:%M:%S') again. This will generate a new string with the time. Once you have assigned the string to timer, it will not change automatically.

The following should work:

import time, datetime
print datetime.datetime.now().strftime('%H:%M:%S') + " This is a test"
time.sleep(5) # 5 seconds until next statement
print datetime.datetime.now().strftime('%H:%M:%S') + " Test after 5 seconds, so the timer should've changed"
于 2013-10-01T10:27:12.960 回答
0

In you code, timer is nothing but a string containing the value of the current time when you ran the code. You are simply printing it out twice, with a 5 second sleep in between. But that will not change its value.

You need to rerun the line: datetime.datetime.now().strftime('%H:%M:%S') every time you want to refresh the time.

于 2013-10-01T10:27:42.270 回答