Home > Software engineering >  RuntimeWarning: DateTimeField Model.date received a naive datetime while time zone support is active
RuntimeWarning: DateTimeField Model.date received a naive datetime while time zone support is active

Time:12-02

I am trying to filter a query set to obtain this year's all posts.

def thisYearQuerySet(objects):
    start_day = datetime.date(datetime.date.today().year, 1, 1)
    end_day = datetime.date(datetime.date.today().year, 12, 31)
    return objects.filter(date__range=[start_day, end_day])

django moans about start_day and end_day declaration may conflicts django.utils.timezone, I think it is not a big deal.


But the warning is annoying, any suggestion on dismissing it (not disable django warning) will be appreciated. something like, how to get first day of the year and the last from django.utils

full warning

RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active.
RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-12-31 00:00:00) while time zone support is active.

CodePudding user response:

django moans about start_day and end_day declaration may conflicts django.utils.timezone, I think it is not a big deal.

This depends on the level of risk you're comfortable with. By not taking into account the user's timezone, thisYearQuerySet could return objects from last year or the current year as you near the new year.

This is because the server could be running at GMT time, which means at 2022-01-01 00:00:00T00:00, it would start returning data with dates of the year 2022. However any Americans using the application would know the year to be 2021 for 4 hours yet and would expect to see 2021's data until their own midnight.

However, if you're trying to silence the warning and don't care about the above scenario, don't use the python datetime functions when getting today/now. Use:

from django.utils import timezone
now = timezone.now()
today = timezone.now().date()
  • Related