实时访问时间

时间:2015-02-21 02:21:22

标签: python loops time

我正在尝试使用以下代码在每分钟的前45秒进行循环运行。但是当我获得秒时,变量只存储第二个值在那个确切的时间。如何让变量每秒不断更新?

我的代码:

i = time.strftime("%S")
print i   

while i < 45:
    ...

3 个答案:

答案 0 :(得分:2)

如果您希望每秒连续循环打印作为倒数计时器:

from datetime import timedelta,datetime
import time

while True:
    if not datetime.now().second: # make sure we start first run at start of minute
        t = timedelta(seconds=45)
        while t:
           t -= timedelta(seconds=1)
           time.sleep(1)
           print(t)
        time.sleep(15) # sleep for 15 seconds before starting again
        t = timedelta(seconds=45)

如果您不关心第一次开始时间并且想要计算:

from datetime import datetime
import time

while True:
    for sec in iter(lambda: datetime.now().second, 46):
        print(sec)
        time.sleep(1)
    time.sleep(14)  # sleep for 14 seconds before starting again

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
..............

答案 1 :(得分:0)

time.time()会在午夜后的几秒钟内给你时间。

import time
current_time = time.time()
time.sleep(6) #Delay Deliberately
print time.time() - current_time

答案 2 :(得分:0)

不漂亮,但我按照以下方式开始工作:

c = 1

while c < 2:
        i = float( time.strftime("%S"))
        while i < 30:
           i = float(time.strftime("%S"))