如何在 django 中按天过滤日期时间并了解时区 utc?

问题描述 投票:0回答:1

我尝试过滤的日期时间对象是数据库中的 2024-10-26 00:49:34.131805,在我的国家是晚上 9 点。发生的情况是,当我尝试按天过滤时(created_at__day=timezone.now().day),它返回第26天,这是可以的,但是django在过滤时将它们转换为正确的时区(前一天晚上9点)并结束值不匹配

我需要做什么?

设置.py

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = True

模型.py

created_at = models.DateTimeField(auto_now_add=True)

查询

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

这就是我尝试过的

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

这有效... 但我真的想只按白天进行过滤。 django 提供了一些东西还是我做错了什么?

python django datetime filter timezone
1个回答
0
投票

您可以按

created_at__range
筛选:

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

# Example: Filter records created today in America/Sao_Paulo time
now = timezone.now()

# Convert current time to "America/Sao_Paulo" timezone
local_now = now.astimezone(timezone.get_current_timezone())
start = local_now.replace(hour=0, minute=0, second=0, microsecond=0)
end = local_now.replace(hour=23, minute=59, second=59, microsecond=999999)

# Query records created within this day in local time
filtered_records = Model.objects.filter(created_at__range=(start, end))
© www.soinside.com 2019 - 2024. All rights reserved.