Timezone warning from date filtering via the ORM

I have a project which was recently upgraded to 4.0.1 from 3.1 and I’m trying to quash some of the native date time warnings I have been receiving. When I filter a DateTimeField by making reference to a DateField I get warnings.

class Note(models.Model):
    date = models.DateTimeField(default=timezone.now)

class Season(models.Model):
    start_date = models.DateField()

# In settings.py
USE_TZ = True
TIME_ZONE = 'US/Pacific'
US_PACIFIC_TIMEZONE = pytz.timezone('US/Pacific')

When I do a query such as Note.objects.filter(date__gte=date(2021,1,1)) I get a warning that RuntimeWarning: DateTimeField Note.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active. Which I suppose makes sense since in that example I’m specifying a date with no timezone. But I also get this when I try to filter by the date field of another model, Note.objects.filter(date__gte=my_season.start_date)

First question: my understanding is that pytz is on it’s way out, but what is the correct way to handle this instead? This app runs in a single timezone and always will.

Second question: if I am solving question 1 the correct way, will I always have to explicitly convert my DateFields to be timezone aware in order to filter a DateTimeField? And how do I even do that?



Also a problem because your start_date field is a date field without a time.

If note.date is 2022-01-24 22:00:00 -0700, is it before or after 2022-01-25 00:00:00 +???. It kinda depends upon what that “assumed” timezone would be for that date. By not specifying a timezone, PostgreSQL may or may not make the right assumption.

Yes. (Well, I guess you could use the Trunc function to truncate the datetime field to the “date” level and perform your comparison on it. But I’m pretty sure that’s more involved and would need to be verified and validated in your specific situation.)

See the make_aware function.

1 Like

Thanks, that answered my question and solves the errors.