Reputation: 33
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'
Upvotes: 1
Views: 2315
Reputation: 52133
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.
Upvotes: 2