我需要确定在给定开始和停止时间的情况下是否应该停止或启动服务 例如
start_time = '16:00'
stop_time = '7:50'
如果现在时间是16:50,则该服务应正在运行;如果现在时间是14:00,则应停止该服务
start_time = '7:00'
stop_time = '20:00'
如果现在的时间是7:05,则该服务应该正在运行;如果现在的时间是21:00,则应该停止该服务...您知道了
到目前为止,我已经有了这个,但是还无法弄清楚逻辑;
import datetime
def test_time(start_time, stop_time):
now = datetime.datetime.now()
current_hour = int(now.hour)
current_minute = int(now.minute)
start_hour, start_minute = start_time.split(':')
stop_hour, stop_minute = stop_time.split(':')
print(f"hour: {current_hour}, minute: {current_minute}")
答案 0 :(得分:1)
使用datetime
将文本时间转换为time
。这为您提供了应该开启服务的时间间隔。如果这段时间在午夜前后结束,则将其分成两个间隔。
然后,只需检查一下当前时间是否在on
周期或off
周期内;还要检查服务状态。如果两者不匹配,则启动/停止服务。
def sync_service(start_time, stop_time):
# start_time and stop_time are "datetime" items.
service_on = # Check status of service; return boolean
now = datetime.datetime.now()
# If interval wraps around midnight, then switch times
# to check when service is *off*
wrap_interval = stop_time < start_time
if wrap_interval:
start_time, stop_time = stop_time, start_time
# Should the service be on now?
# Check whether we're within the daily interval,
# and what type of interval we have (on or off)
want_service_on = wrap_interval != (start_time < now < stop_time)
# Adjust service status, if necessary
if want_service_on and not service_on:
service.start()
if not want_service_on and service_on:
service.stop()
这能让你前进吗?