DJango Queryset comparing date time

Good day to all developers. Today encountered this issue where I do a simple queryset in DJango and hit with the following warning message:

 RuntimeWarning: DateTimeField MessageContent.send_time received a naive datetime (2014-05-14 04:46:30.392000) while time zone support is active.

How is this happen? This is due to I do the following datetime comparison in my queryset:

import datetime

Item.objects.filter(created = datetime.datetime.now())

The error is due to TIME_ZONE (in settings.py) is enabled by default.
So the solution for this is pretty simple:
1) Either to set the TIME_ZONE to False in settings.py ( this will take away the timezone capability of your application)
2) or by comparing to timezone enabled datetime which the code as below:

import datetime

from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)
Item.objects.filter(created = now)

With this, the problem has been solved. More information can be found in Django website:


Thanks for reading and have a nice coding day!!!

Comments

Popular posts from this blog

Django Form: MultipleChoiceField and How To Have Choices From Model Example

Jquery Validation fix for date format dd/mm/yyyy in Chrome and Safari