如何检查给定的日期时间对象是否在两个日期时间之间?

14
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()

如何检查当前时间是否在它们之间?

my_event.start_time < current_time < my_event.end_time
5个回答

11

只要start_time和end_time没有关联的tzinfo类,您的答案就是正确的选择。不能直接比较一个naive datetime与具有时区信息的datetime。


11

你可以使用一个简单的if语句比较三个日期,像这样:

if date1 < yourdate < date2:
  ...do something...
else:
  ...do ...

3

我知道这个问题很老,但是由于在谷歌搜索结果中排名很高,这里的答案没有考虑以下两种情况:

  1. 如果你的时间等于你的范围之一,例如你的范围是6-8,而现在时间是6点。
  2. 如果你的时间范围是18:00到6:00,那么19:00不在有效范围内。

我编写了一个函数来比较时间,希望这能帮助任何查看这个旧问题的人。

def process_time(intime, start, end):
    if start <= intime <= end:
        return True
    elif start > end:
        end_day = time(hour=23, minute=59, second=59, microsecond=999999)
        if start <= intime <= end_day:
            return True
        elif intime <= end:
            return True
    return False

0

被测试的日期时间需要全部是naive(无时区)或全部是aware(有时区)。如果尝试比较aware和naive,则应该出现异常。如果所有日期时间都是aware,则时区实际上不必匹配,因为在比较时会考虑到这一点。

例如:

class RND(datetime.tzinfo):
    """ Random timezone UTC -3 """

    def utcoffset(self, dt):
        return datetime.timedelta(hours=-3)

    def tzname(self, dt):
        return "RND"

    def dst(self, dt):
        return datetime.timedelta(hours=0)


april_fools = datetime.datetime(year=2017, month=4, day=1, hour=12, tzinfo=pytz.UTC)

random_dt = datetime.datetime(year=2017, month=4, day=1, hour=9, tzinfo=RND())

random_dt == april_fools
# True as the same time when converted back to utc.

# Between test of 3 naive datetimes
start_spring = datetime.datetime(year=2018, month=3, day=20)
end_spring = datetime.datetime(year=2018, month=6, day=21)
april_fools = datetime.datetime(year=2018, month=4, day=1)


if start_spring < april_fools < end_spring:
    print "April fools is in spring"

0
这是我检查两个不同时间段之间时间的脚本。一个是早上,一个是晚上。这是使用@ Clifford的脚本扩展的脚本。
def Strategy_Entry_Time_Check():
    current_time = datetime.datetime.now()
    #current_time = current_time.replace(hour=13, minute=29, second=00, microsecond=00) #For testing, edit the time
    morning_start = current_time.replace(hour=9, minute=30, second=00, microsecond=00)
    morning_end = current_time.replace(hour=11, minute=00, second=00, microsecond=00)
    evening_start = current_time.replace(hour=13, minute=00, second=00, microsecond=00)
    evening_end = current_time.replace(hour=15, minute=00, second=00, microsecond=00)
    
    if morning_start <= current_time <= morning_end:
        print("Morning Entry")
        return True
    elif evening_start <= current_time <= evening_end:
        print("Evening Entry")
        return True
    print("No Entry")
    return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接