Skip to content
Advertisement

How do I force Django queryset return datetime field in current timezone?

I have Django model:

class Deal(models.Model):
    ...
    created_at = models.DateTimeField(auto_now_add=True)

When I get created_at value by queryset, it always return to me the datetime value with tzinfo=<UTC> like this:

Deal.objects.filter(id=62).values('created_at')
<QuerySet [{'created_at': datetime.datetime(2015, 10, 26, 4, 10, 54, 997000, tzinfo=<UTC>)}]>

How do I force queryset return datetime value in current timezone (e.g Asia/Ho_Chi_Minh)?

Advertisement

Answer

Django always saves datetimes in UTC, and they are usually returned in UTC as well (depending on the database and database adapter settings). You normally select a timezone by using activate(). That affects various things, like the way datetimes are displayed in templates.

If you want to explicitly convert the timezone for some reason, you can easily do that with localtime(). For example:

from django.utils.timezone import localtime
import pytz

tz = pytz.timezone("Asia/Ho_Chi_Minh")
deals_utc = Deal.objects.filter(id=62).values("created_at")
deals_local = {"created_at": localtime(dt, tz) for dt in deals_utc.values()}
Advertisement