How to check if the current time is in range in python?

泄露秘密 提交于 2019-11-27 04:48:20

The Python solution is going to be much, much shorter.

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

Use the datetime.time class for start, end, and x.

>>> import datetime
>>> start = datetime.time(23, 0, 0)
>>> end = datetime.time(1, 0, 0)
>>> time_in_range(start, end, datetime.time(23, 30, 0))
True
>>> time_in_range(start, end, datetime.time(12, 30, 0))
False

The concept of a datetime.time for tomorrow is void, because datetime.time can't represent this information. You should convert everything to datetime.datetime before comparing:

def time_in_range(start, end, x):
    today = datetime.date.today()
    start = datetime.datetime.combine(today, start)
    end = datetime.datetime.combine(today, end)
    x = datetime.datetime.combine(today, x)
    if end <= start:
        end += datetime.timedelta(1) # tomorrow!
    if x <= start
        x += datetime.timedelta(1) # tomorrow!
    return start <= x <= end

Calculations involving date/time can be very tricky, there is an enlightening video from the talk by Taavi Burns at PyCon2012 entitled "What you need to know about datetimes":

What you need to know about datetimes:
time, datetime, and calendar from the standard library are a bit messy. Find out: what to use where and how (particularly when you have users in many timezones), and what extra modules you might want to look into.

Event: PyCon US 2012 / Speakers: Taavi Burns / Recorded: March 10, 2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!