. Advertisement .
..3..
. Advertisement .
..4..
I’m building a new program, but when I run it, an error pops up. The error displayed is as follows:
TypeError: can't compare offset-naive and offset-aware datetimes
I have tried several workarounds, but they still do not get the desired results. If you have come across this situation and have a solution for the “can’t compare offset-naive and offset-aware datetimes” problem, pls let me know. Here is what I do:
if challenge.datetime_start <= datetime.now() <= challenge.datetime_end:
class Fundraising_Challenge(models.Model):
name = models.CharField(max_length=100)
datetime_start = models.DateTimeField()
datetime_end = models.DateTimeField()
Thanks!
The cause:
This error happens due to both of datetime.datetime.now() and datetime.datetime.utcnow() are unaware the time zones.
Solution:
By default,
naive
isdatetime
object in Python, so it’s essential to make them aware ofdatetime
objects. You can do this by:An important thing you need to note is that if
tzinfo
has already been set, this would raiseValueError
. You can use these following command to check:A UNIX timestamp also could be formatted by using datetime.datetime object and timezone information as follows:
datetime.datetime.now
does not recognize time zones.Django includes a helper to do this. This requires
pytz
It should be possible to compare
now
andchallenge.datetime_start