SQL中的子句和Django时区



我注意到,当我使用以下内容从SQL数据库返回记录时:the_records = records.objects.filter(datetime__contains="2015-01-15"),我会恢复错误的记录我暂时禁用时区,返回正确的记录。任何人都可以为解决此问题提供帮助(我仍然需要使用时区)。

标记,马克

我假设datetime是DJANGO DateTime字段,您正在尝试获取具有与日期'2015-01-15'的值的结果实际时间。

在这种情况下,您可能想进行date查询,例如:Records.objects.filter(datetime__date=datetime.date(2015, 1, 15))

如果您需要使用特定时间区域的日期查询数据库,则可以创建一个dateTime对象,该对象知道它的时区。

示例:

# Get your timezone
from django.utils import timezone
my_timezone = timezone.get_current_timezone()

# Get create your timezone aware datetime object
from datetime import datetime
query_date = datetime(2015,01,15).replace(tzinfo=my_timezone)

# now you can run your query with a timezone specific datetime object
the_records = records.objects.filter(datetime=query_date)

这应该解决您的问题,并为您提供所需的准确结果。请让我知道您是否还有任何疑问。

如果您有兴趣了解更多信息,则此链接具有与Django时区有关的更多信息。

最新更新