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

前端 未结 4 1929
耶瑟儿~
耶瑟儿~ 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:32

    The datetimes getting tested need to all naive (no timezone) or all aware (timezone). An exception should occur if you try to compare aware and naive. If all the datetimes are aware the timezones don't actually have to match that appears to be taken into consideration when comparing.

    e.g.

    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"
    

提交回复
热议问题