How do I check if a given datetime object is “between” two datetimes?

前端 未结 4 2033
耶瑟儿~
耶瑟儿~ 2021-02-14 12:05
my_event = Event.objects.get(id=4)
current_time = datetime.datetime.now()

How do I do check if my current time is between them?

my_eve         


        
4条回答
  •  轮回少年
    2021-02-14 12:34

    I know old, but since this is so high on Google results, answers here don't take into consideration two cases:

    1. If your time equals either of your range, ie your range is 6-8 and it is 6.
    2. If your time range is say 18:00 to 6:00, valid range; however 19:00 would not match.

    I wrote a function to take care of time comparison, hope this helps anyone viewing this old question.

    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
    

提交回复
热议问题