[Django]-How can I cast a DateField() + TimeField() to local time in a Django QuerySet?

5👍

Yes. You can use any Postgres function by writing a custom django database function.

Here is a custom django database function for the equivalent of the Postgres at time zone.

Django 4.0
from django.db.models import ExpressionWrapper, F, Func
from django.db import models


class AtTimeZone(Func):
    function = 'AT TIME ZONE'
    template = "%(expressions)s %(function)s '%(timezone)s'"


class SessionQuerySet(models.QuerySet):
    def with_datetimes(self):
        return self.annotate(
            start_datetime=ExpressionWrapper(
                F('date') + F('start_time'),
                output_field=models.DateTimeField()
            ),
            end_datetime=ExpressionWrapper(
                F('date') + F('end_time'),
                output_field=models.DateTimeField()
            ),
            start_local_datetime=AtTimeZone(F('start_datetime', timezone='Europe/Berlin')
        )

The above is for a model with the initial fields of: date, start_time, and end_time.

Here are the docs regarding django’s custom database functions. https://docs.djangoproject.com/en/4.0/ref/models/expressions/#func-expressions.
As of the start of 2022, the docs don’t provide many examples on how to create custom database functions. This should help.

👤TD1

-2👍

I think you can use the library pytz (https://pypi.org/project/pytz/) to localize the naive datetime.

from datetime import datetime
from pytz import timezone

tz = timezone('Europe/Amsterdam')
naive_dt = datetime(2021, 9, 20, 17, 0)
localized_dt = tz.localize(naive_dt)
print(localized_dt)

Leave a comment