Python

Django – creating timezone aware datetime objects

After developing some codes for few hours, when I finally tried to test it, I am greeted with this timezone related error. After reviewing Django docs, it is clearly stated that it has full support for timezones and that it will automatically take care of timezones at model layer. I’ve found out that it is not to hard to get it right, the Django way.

Problem?

Below is the code that caused the error (inside a model) where expires_in is a DateTimeField:

if self.expires_in and self.expires_in > datetime.datetime.now():

Below is the error I’ve encountered:

TypeError: can't compare offset-naive and offset-aware datetimes

The field expires_in is a field in a model which is a timezone aware datetime object. However, the .now() is a naive datetime object, causing the error described above.

Fix?

Instead of using the native datetime, we can utilize some Django’s utility modules that handles timezone properly. We just need to use the django.utils.timezone.now() method to create a timezone aware datetime object.

from django.utils import timezone
# ...
# ...
if self.expires_in and self.expires_in > timezone.now():

That’s it! I wonder what the code looks like to create datetime other than now.

Leave a reply

Your email address will not be published. Required fields are marked *