当前时间等于另一个时间时如何使用函数:Python
How to use a function when the current time equals another time: Python
我正在开发一个脚本,该脚本利用我制作的功能来控制 Raspberry Pi 3 上 8 通道继电器板的继电器。该功能有效,并且调用该功能有效。我正在尝试开发此脚本,因此当当前时间等于另一个时间时,例如区域 1 开始时间,继电器将根据代码中另一部分接收到的状态转动 on/off。
我已经测试过了,没有这个时间等于部分,一切正常。当我添加这种级别的复杂性时,我似乎 运行 遇到了一些问题。这是我的代码示例:
while True:
from datetime import datetime
import time
import smbus
ValveStatus='00000001' #0 is closed, 1 is open.
R1_1,R2_1,R3_1,R4_1,R5_1,R6_1,R7_1,R8_1=list(map(int, ValveStatus))
currenttime=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
Z1S_Timestamp='2018-07-09 10:25:11'
if(currenttime==Z1S_Timestamp):
if(R8_1==1):
SetRelayState(BoardOne,8,"ON")
else:
SetRelayState(BoardOne,8,"OFF")
无论我改了多少次代码,这种计时方法都行不通。它永远不会进入回路,因此继电器永远不会打开。有没有更好的方法来做到这一点,而不是简单地使用 if equal to 语句?我愿意编辑它,但继电器仍然需要在开始时间左右打开。我认为 1 或 2 分钟的余量是可以的,因为并非 100% 需要完全相等的时间。
会是这样的:
currenttime= '2018-07-09 12:53:55' #hard coding just for example purposes
if('2018-07-09 12:52:55' <= currenttime <= '2018-07-09 12:54:55'):
do the things
是一个更valid/correct/pythonically正确的方法?
当然 - 我会做相反的事情 - 将所有时间转换为 datetime()
对象并使用它们进行比较:
TIME_MARGIN = datetime.timedelta(seconds=120) # use a margin of 2 minutes
time_compare = datetime.datetime(2018, 7, 9, 12, 52, 55)
current_time = datetime.datetime.now()
if (time_compare - TIME_MARGIN) < current_time < (time_compare + TIME_MARGIN):
#do something
我正在开发一个脚本,该脚本利用我制作的功能来控制 Raspberry Pi 3 上 8 通道继电器板的继电器。该功能有效,并且调用该功能有效。我正在尝试开发此脚本,因此当当前时间等于另一个时间时,例如区域 1 开始时间,继电器将根据代码中另一部分接收到的状态转动 on/off。
我已经测试过了,没有这个时间等于部分,一切正常。当我添加这种级别的复杂性时,我似乎 运行 遇到了一些问题。这是我的代码示例:
while True:
from datetime import datetime
import time
import smbus
ValveStatus='00000001' #0 is closed, 1 is open.
R1_1,R2_1,R3_1,R4_1,R5_1,R6_1,R7_1,R8_1=list(map(int, ValveStatus))
currenttime=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
Z1S_Timestamp='2018-07-09 10:25:11'
if(currenttime==Z1S_Timestamp):
if(R8_1==1):
SetRelayState(BoardOne,8,"ON")
else:
SetRelayState(BoardOne,8,"OFF")
无论我改了多少次代码,这种计时方法都行不通。它永远不会进入回路,因此继电器永远不会打开。有没有更好的方法来做到这一点,而不是简单地使用 if equal to 语句?我愿意编辑它,但继电器仍然需要在开始时间左右打开。我认为 1 或 2 分钟的余量是可以的,因为并非 100% 需要完全相等的时间。
会是这样的:
currenttime= '2018-07-09 12:53:55' #hard coding just for example purposes
if('2018-07-09 12:52:55' <= currenttime <= '2018-07-09 12:54:55'):
do the things
是一个更valid/correct/pythonically正确的方法?
当然 - 我会做相反的事情 - 将所有时间转换为 datetime()
对象并使用它们进行比较:
TIME_MARGIN = datetime.timedelta(seconds=120) # use a margin of 2 minutes
time_compare = datetime.datetime(2018, 7, 9, 12, 52, 55)
current_time = datetime.datetime.now()
if (time_compare - TIME_MARGIN) < current_time < (time_compare + TIME_MARGIN):
#do something