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

后端 未结 9 1272
离开以前
离开以前 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:47

    Do this in settings.py file :

    USE_TZ=False

    I was getting the same error, and it has resolved the error

    0 讨论(0)
  • 2020-12-02 08:53

    One line of code solution

    if timezone_aware_var <= datetime.datetime.now(timezone_aware_var.tzinfo):
        pass #some code
    

    Explained version

    # Timezone info of your timezone aware variable
    timezone = your_timezone_aware_variable.tzinfo
    
    # Current datetime for the timezone of your variable
    now_in_timezone = datetime.datetime.now(timezone)
    
    # Now you can do a fair comparison, both datetime variables have the same time zone
    if your_timezone_aware_variable <= now_in_timezone:
        pass #some code
    

    Summary

    You must add the timezone info to your now() datetime.
    However, you must add the same timezone of the reference variable; that is why I first read the tzinfo attribute.

    0 讨论(0)
  • 2020-12-02 08:57

    Disable time zone. Use challenge.datetime_start.replace(tzinfo=None);

    You can also use replace(tzinfo=None) for other datetime.

    if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):
    
    0 讨论(0)
提交回复
热议问题