Python - 如果现在时间介于两次之间,则计算出来

时间:2013-12-11 11:38:52

标签: python python-2.7 python-3.x scheduled-tasks schedule

我正试图找到最干净/最pythonic的方式来评估“现在”是否介于两次之间;然而;开始/结束时间可能会或可能不会落在一天的边界 - 例如(仅使用简单示例):

onhour=23
onmin=30
offhour=4
offmin=15
timenow = datetime.datetime.now().time()

执行直接if START < NOW < END方案对此无效!

我目前所拥有的是一些代码,用于评估当前是否为“NightTime”,如下所示:

def check_time(timenow, onhour, onmin, offhour, offmin, verbose):
    now = datetime.datetime.now()
    now_time = now.time()
    # If we're actually scheduling at night:
    if int(offhour) < int(onhour):
        # Check to see if we're in daylight times (ie. off schedule)
        if datetime.time(int(offhour),int(offmin)) <= now_time <= datetime.time(int(onhour),int(onmin)):
            if verbose == True:
                print("Day Time detected.")
            return False
        else:
            if verbose == True:
                print("Night Time detected.")
            return True
    else:
        if datetime.time(int(onhour),int(onmin)) <= now_time <= datetime.time(int(offhour),int(offmin)):
            if verbose == True:
                print("Night Time detected.")
            return True
        else:
            if verbose == True:
                print("Day Time detected.")
            return False

道歉,如果标题听起来不像什么新内容,但已经审查了类似问题的一些现有答案,例如:

我注意到这些似乎并不考虑开始时间和结束时间超过一天边界的情况。

除此之外;任何有关添加基于日期的日程安排的想法都会非常有用!即。 “对于周一至周五,在凌晨4点开始,在凌晨4点关闭” - 但是在任何一方都可以打开和关闭一天(否则;星期五将会打开一些东西,但星期六不会关闭 - 但是,包括星期六意味着它会在23点重新开启!......)

我考虑做一个简单的“在X上打开,为Y睡觉”来解决这个问题......但是如果脚本在“开启”周期内启动,它将在下一个周期启动跑...但它似乎是最简单的选择! :)

我希望有一些很棒的模块可以做到这一切......:D

Python2.7的兼容性 - 3.2对我来说也很重要!

4 个答案:

答案 0 :(得分:9)

要确定给定的开始时间,结束时间(不包括结尾)之间是否存在给定时间(无日期):

def in_between(now, start, end):
    if start <= end:
        return start <= now < end
    else: # over midnight e.g., 23:30-04:15
        return start <= now or now < end

示例:

from datetime import datetime, time

print("night" if in_between(datetime.now().time(), time(23), time(4)) else "day")

答案 1 :(得分:3)

你的代码有点混乱。我会做这样的事情:

import datetime

DAY, NIGHT = 1, 2
def check_time(time_to_check, on_time, off_time):
    if on_time > off_time:
        if time_to_check > on_time or time_to_check < off_time:
            return NIGHT, True
    elif on_time < off_time:
        if time_to_check > on_time and time_to_check < off_time:
            return DAY, True
    elif time_to_check == on_time:
        return None, True
    return None, False


on_time = datetime.time(23,30)
off_time = datetime.time(4,15)
timenow = datetime.datetime.now().time()
current_time = datetime.datetime.now().time()

when, matching = check_time(current_time, on_time, off_time)

if matching:
    if when == NIGHT:
        print("Night Time detected.")
    elif when == DAY:
        print("Day Time detected.")

答案 2 :(得分:0)

def is_hour_between(start, end, now):
    is_between = False

    is_between |= start <= now <= end
    is_between |= end < start and (start <= now or now <= end)

    return is_between

测试:

assert is_hour_between(6, 10, 6)
assert not is_hour_between(6, 10, 4)
assert is_hour_between(17, 20, 17)
assert not is_hour_between(17, 20, 16)

答案 3 :(得分:0)

Kevron 的帖子实际上帮助解决了我的问题。我的要求与我传递字符串的地方略有不同。我的版本是这样的:

def is_hour_between(start, end):
    # Time Now
    now = datetime.datetime.now().time()
    # Format the datetime string
    time_format = '%Y-%m-%d %H:%M:%S'
    # Convert the start and end datetime to just time
    start = datetime.datetime.strptime(start, time_format).time()
    end = datetime.datetime.strptime(end, time_format).time()

    is_between = False
    is_between |= start <= now <= end
    is_between |= end <= start and (start <= now or now <= end)

    return is_between

check = is_hour_between('2021-04-07 08:30:00', '2021-04-07 04:29:00') #spans to the next day
print("time check", check) # result = True

希望这能帮助那些在字符串时间方面苦苦挣扎的人。