pythondjangodatetimefiltertimezone

how to filter datetime by day in django with timezone utc aware?


The datetime objects I am trying to filter are 2024-10-26 00:49:34.131805 in the database, which is 9pm in my country. what happens is that when I am trying to filter by day (created_at__day=timezone.now().day) it returns day 26, which is ok, but Django translates them to the correct timezone (9pm the previous day) when filtering and ends up mismatching values.

What I need to do?

settings.py

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = True

models.py

created_at = models.DateTimeField(auto_now_add=True)

query

day = timezone.now().day
filter = Model.objects.filter(created_at__day=day)

this is what i tried

date = timezone.now()
filter = Model.objects.filter(created_at__date=date)

and that worked... but i really wanted to filter just by day. Does Django provide something or am I doing something wrong?


Solution

  • You may can filter by range and set the start and end time of the day:

    from datetime import timedelta
    from django.utils import timezone
    
    now = timezone.localtime(timezone.now())
    
    start = now.replace(hour=0, minute=0, second=0, microsecond=0)
    end = start_of_day + timedelta(days=1)
    
    result = Model.objects.filter(
        created_at__gte=start,
        created_at__lt=end,
    )
    

    Pay attention to not use filter as variable, because that is a built in Python function.