1

I would like to get all objects from last hour. For example: I have 13:58 and i would like to get all objects from 13 to 14

This is my code:

now = datetime.datetime.now()
earlier = now - datetime.datetime(now.year, now.month, now.day, now.hour, 0,0)
MyModel.objects.filter(date__range=(earlier, now))

but I have an error:

RuntimeWarning: DateTimeField MyModel.date received a naive datetime (2018-02-14 17:16:58.478000) while time zone support is active.
RuntimeWarning)

My settings:

USE_TZ = True 
TIME_ZONE = 'Europe/Warsaw'
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
Kuba K
  • 33
  • 1
  • 7
  • Possible duplicate of [DateTimeField received a naive datetime](https://stackoverflow.com/questions/21038881/datetimefield-received-a-naive-datetime) – shad0w_wa1k3r Feb 14 '18 at 17:19

1 Answers1

2

You are trying to compare a naive date with a time-aware one. When timezone is enabled in settings.py, you should use django.utils.datetime.now() over the builtin datetime.datetime.now() which is naive when doing comparison or filtering.

>>> from datetime import timedelta
>>> from django.utils import timezone

>>> this_hour = timezone.now().replace(minute=0, second=0, microsecond=0)
>>> one_hour_later = this_hour + timedelta(hours=1)
>>> MyModel.objects.filter(date__range=(this_hour, one_hour_later))

You can check out the docs to find out more about how Django handles date times.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119