Can't compare naive and aware datetime.now() <= challenge.datetime_end

后端 未结 9 1290
离开以前
离开以前 2020-12-02 07:58

I am trying to compare the current date and time with dates and times specified in models using comparison operators:

if challenge.datetime_start <= datet         


        
9条回答
  •  死守一世寂寞
    2020-12-02 08:31

    By default, the datetime object is naive in Python, so you need to make both of them either naive or aware datetime objects. This can be done using:

    import datetime
    import pytz
    
    utc=pytz.UTC
    
    challenge.datetime_start = utc.localize(challenge.datetime_start) 
    challenge.datetime_end = utc.localize(challenge.datetime_end) 
    # now both the datetime objects are aware, and you can compare them
    

    Note: This would raise a ValueError if tzinfo is already set. If you are not sure about that, just use

    start_time = challenge.datetime_start.replace(tzinfo=utc)
    end_time = challenge.datetime_end.replace(tzinfo=utc)
    

    BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following

    d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
    d_with_tz = datetime.datetime(
        year=d.year,
        month=d.month,
        day=d.day,
        hour=d.hour,
        minute=d.minute,
        second=d.second,
        tzinfo=pytz.UTC)
    

提交回复
热议问题