给定开始和停止时间,检查是否应开启服务

时间:2019-06-06 16:02:07

标签: python

我需要确定在给定开始和停止时间的情况下是否应该停止或启动服务 例如

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}")

1 个答案:

答案 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()

这能让你前进吗?