Django: can’t compare offset-naive and offset-aware datetimes error


I encountered an horrible problem today, and I wants to share the solution with you. So I decided to write this post. The problem was: can’t compare offset-naive and offset-aware datetimes. The origin of this error is a compare between an offset-aware date time, obtained from the database in my case, and an offset-naive date time, this is the default type of python datetime object. Below the line that caused this error:

from datetime import timedelta, datetime

one_hour_ago = datetime.now() - timedelta(hours=1)
if topic.created > one_hour_ago:
    # Do something

So the solution is to make both of compared datetime to either naive or aware datetime object. Fortunately, Django comes with a helper to solve this problem:

>>> from django.utils import timezone
>>> now = timezone.now()
datetime.datetime(2013, 12, 11, 9, 43, 44, 868854, tzinfo=<UTC>)

Now, “now” is an offset-aware datetime object. For non djangonauts developer, you can use pytz python module like that:

>>> from datetime import datetime
>>> import pytz
>>> utc = pytz.UTC
>>> now = utc.localize(datetime.now())
datetime.datetime(2013, 12, 11, 9, 43, 44, 868854, tzinfo=<UTC>)
Advertisements

One thought on “Django: can’t compare offset-naive and offset-aware datetimes error

  1. Undeniably consider that that you stated. Your favourite justification seemed
    to be at the internet the simplest thing to take into account of.
    I say to you, I definitely get annoyed whilst other folks
    consider issues that they just do not know about.
    You managed to hit the nail upon the highest as smartly as defined
    out the entire thing with no need side effect , other people can take a signal.
    Will probably be back to get more. Thank you

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s