2017-06-19 84 views
-1

我想一个函数开始到分钟的第一秒运行的第一秒运行,但我不能做到这一点 这是我的代码功能开始在分钟

import datetime 
now = datetime.datetime.now() 
while not (now.second == "01"):now = datetime.datetime.now() 
+0

你是指什么在一分钟的第一秒跑?你的意思是每分钟运行一次? – depperm

+0

这里有很多没有解释。最终目标是什么? – pstatix

回答

1
import time 
while True: 
    if time.strftime("%S") == "01": 
     #Run Your Code 
     time.sleep(59) 
1

这将砸向你的系统像疯了似的,给它一点呼吸的空间:

import time 

while True: 
    current_seconds = time.gmtime().tm_sec 
    if current_seconds == 1: 
     print("The first second of a minute...") 
    time.sleep(0.9) # wait at least 900ms before checking again 

您可以进一步通过计算多少时间,你又开始检查前要等待精简它 - 如果你有兴趣在在第一秒钟内,您可以安全入睡,直到一分钟结束。

2

您的代码不起作用,因为您将一个数字(now.second)与字符串"01"进行比较。在Python编号和它们的字符串表示方式并不相同(不像其他一些编程语言),所以这不会起作用。

尝试与1比较(或者如果您真的想要一分钟的话,可以输入0)。也许不是忙碌循环(在等待时将使用您的CPU的全部核心),您应该使用time.sleep来等待下一分钟的开始。

import datetime 
import time 

now = datetime.datetime.now() 
sec = now.second 
if sec != 0: 
    time.sleep(60-sec) 
# it should be (close to) the top of the minute here! 

随着时间的计算机上打交道时,因为你的程序可能会与在任何时刻(更可能,如果你的CPU是非常繁忙)由操作系统上运行被推迟总是有一些不可预测性。虽然我不太担心,但可能会非常接近正确的时间。