Make specific DateTimeFields without timezone

My Django project correctly has timezones enabled and it always stores times with timezone in the Postgres database.

There is just one table my project needs to access that is managed by another application. To access this other table I have configured a second database, a database router, and an unmanaged model. It all works perfectly.

However, this external table has some DateTimeFields that are without timezone. This is not my choice, but I have no control over it. The result is that when working with this model, Django will spit out many of the “received a naive datetime” warnings. Is there any way to tell Django that I know those specific DateTimeFields are not timezone aware, and that it should not warn me when they receive naive datetimes?

I’m not sure I’m clear on what you’re trying to describe here.

What I believe you’re saying is that you have a model associated with a table storing non-timezone-aware values.

When you issue a query that retrieves a row containing one of those values, you’re getting the warning.

Is that what you’re saying here? Or are you describing some other situation where this is happening?

Step 1: Make a new Django project with the default setting of USE_TZ=True and a PostgreSQL database.

Step 2: Do this directly in PostgreSQL.

CREATE TABLE timewarningtest (
    mytimefield timestamp without time zone
);

INSERT INTO timewarningtest (
    mytimefield
) SELECT
    CURRENT_TIMESTAMP
;

Step 3: Create this Django model:

from django.db import models

class TimeWarningTest(models.Model):
    mytimefield = models.DateTimeField()

    class Meta:
        managed = False
        db_table = "timewarningtest"

Step 4: Use the Django model to write to the table

test_row = TimeWarningTest.objects.all().first()
test_row.save()

Actual Result: There is a RuntimeWarning about receiving a naive datetime while time zone support is active.

Desired Result: No warning because this is a special case where we know the time is naive. There should be some way to indicate to the Django model that this specific DateTimeField is an exception, and it’s OK if it is a naive time with no timezone

Perhaps something like this:

mytimefield = models.DateTimeField(use_tz=False)

or

mytimefield = models.DateTimeField(naive=True)

or

mytimefield = models.NaiveDateTimeField()

Ok, so you’re not getting the error on the query, you’re getting it when trying to save it.

What you want to do is convert that time to a timezone-aware value when assigning it to the field. See the make_aware function.

Oh, thanks. I suppose that works to avoid the error. It just seems a bit silly to go through the trouble of adding the time zone when it’s just going to be thrown out as the database column can’t accommodate it.