首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在同一功能中处理日期滚转

问在同一功能中处理日期滚转
EN

Code Review用户
提问于 2017-01-22 14:41:26
回答 1查看 288关注 0票数 4

我有一个程序,指定什么时候警报应该是活动的(例如,上午10点到晚上8点)。我的程序的一部分,然后检查警报是否现在是有效的。“it it active”检查器需要处理跨越午夜边界到明天(例如,晚上8点到上午10点警报)的警报范围。

我目前正在使用相同的冗余函数来处理这个问题,除了进行和vs或比较之外。请问有什么更好的方法?(当然,任何其他评论也是最受欢迎的。)

代码语言:javascript
复制
import datetime as dt

def check_alarm_bounds_on_same_date(time_now, time_of_day_bounds):
    time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
    if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) and #<< AND
         time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
        return True
    return False

def check_alarm_bounds_on_different_dates(time_now, time_of_day_bounds):
    time_start_of_current_day = dt.datetime.combine(time_now.date(), dt.datetime.min.time())
    if ( time_now >= (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[0])) or #<< OR
         time_now < (time_start_of_current_day + dt.timedelta(hours=time_of_day_bounds[1])) ):
        return True
    return False

def is_alarm_live(time_current, time_of_day_bounds):
    alarm_start_time = time_of_day_bounds[0]
    alarm_end_time = time_of_day_bounds[1]
    if alarm_end_time <= alarm_start_time:
        return check_alarm_bounds_on_different_dates(time_current, time_of_day_bounds)
    else:
        return check_alarm_bounds_on_same_date(time_current, time_of_day_bounds)

# specify two alarm periods (#1 @ 10AM-8PM; #2 @ 8PM-10AM next day)
alarms = [(10,20),(20,10)]
for hour in range(0,24):
    # test all hours in a sample day, and output which alarm is active
    print 'hour %i: ' % hour,
    time_test = dt.datetime(2017,01,22,hour,10,30)
    for alarm in alarms:
        print is_alarm_live(time_test, alarm),
    print ''
EN

回答 1

Code Review用户

发布于 2017-01-22 21:03:19

非常快速的复习。

  1. 没有文件串。
  2. 代码使用datetime.datetime.combine使datetime.datetime对象表示边界,然后将这些对象与time_current进行比较。但是,让datetime.time对象表示边界,然后将这些对象与time_current.time进行比较会更简单。
  3. 这样做之后,如果函数使用datetime.time对象作为其第一个参数,则会更简单,如果需要的话,则由调用方传递time_current.time。
  4. 这段代码没有什么是特定于警报的(例如,它可以用于约会),所以如果功能是抽象地表达的话,就更容易理解了。

经修订的守则:

代码语言:javascript
复制
import datetime

def time_in_range(time, start_hour, end_hour):
    """Return True if time (a datetime.time object) lies between
    start_hour and end_hour (inclusive).

    >>> time_in_range(datetime.time(hour=12), 10, 14)
    True

    The range is allowed to span midnight:

    >>> time_in_range(datetime.time(hour=0), 22, 2)
    True

    """
    start = datetime.time(hour=start_hour)
    end = datetime.time(hour=end_hour)
    if end <= start: # Range spans midnight.
        return start <= time or time <= end
    else:
        return start <= time <= end
票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/153304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档