Search code examples
djangodjango-timezone

How to query in django datetimefield with default timezone.now for a specific day?


I have a model Game with datetimefield set to default timezone.now().

class Game(models.Model):
    time = models.DateTimeField(default=timezone.now, blank=True, null=True)

I want to query how many games were played on a specific day. I have tried following command and that works fine.

games = Game.objects.filter(time=timezone.now().strftime("%Y-%m-%d"))

But now I want to query Games with filter set to a specific day, let say timezone.now - 1 day. I have tried different variations of timezone.localtime and timezone.localdate and they yield a ValueError.

>>> timezone.localtime(datetime.datetime.now(), timezone.get_default_timezone())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/savi/python-environments/comments/lib/python3.6/site-packages/django/utils/timezone.py", line 207, in localtime
    raise ValueError("localtime() cannot be applied to a naive datetime")
ValueError: localtime() cannot be applied to a naive datetime

I have looked at different questions and other sites and none have suggested any approach for what I am trying to do. Maybe I am not looking at the right places. If someone can guide me through this, I will really appreciate that, Thanks in advance and a very happy new Year.

EDIT I have tried the solution as suggested.

>>> time = timezone.now() - datetime.timedelta(days=1)
>>> time.strftime("%Y-%m-%d")
'2019-12-31'
>>> games = Game.objects.filter(time=time.strftime("%Y-%m-%d")
/home/savi/python-environments/comments/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1427: RuntimeWarning: DateTimeField Game.time received a naive datetime (2019-12-31 00:00:00) while time zone support is active.

RuntimeWarning)

And also

>>> games = Game.objects.filter(time=timezone.now().date())
/home/savi/python-environments/comments/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1369: RuntimeWarning: DateTimeField Game.time received a naive datetime (2020-01-01 00:00:00) while time zone support is active.
  RuntimeWarning)

END OF EDIT

my settings.py file

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Solution

  • But now I want to query Games with filter set to a specific day, let say timezone.now - 1 day

    You can use datetime.timedelta

    games = Game.objects.filter(time = timezone.now() - datetime.timedelta(days=1)))
    

    Edit: for specific day filter you can use __date when filtering

    >>> time = timezone.now() - datetime.timedelta(days=1)
    >>> time.strftime("%Y-%m-%d")
    '2019-12-31'
    >>> games = Game.objects.filter(time__date = time.strftime("%Y-%m-%d"))