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

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


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 datetimeimport pytzutc=pytz.UTCchallenge.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)


datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezonenow = timezone.now()

You should be able to compare now to challenge.datetime_start


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 variabletimezone = your_timezone_aware_variable.tzinfo# Current datetime for the timezone of your variablenow_in_timezone = datetime.datetime.now(timezone)# Now you can do a fair comparison, both datetime variables have the same time zoneif 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.