OiO.lk Blog python how to filter datetime by day in django with timezone utc aware?
python

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


the datetime objects im 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 im 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?



You need to sign in to view this answers

Exit mobile version