gpt4 book ai didi

python - Django:过滤日期之间的数据 | DatetimeField 收到了一个天真的日期时间

转载 作者:行者123 更新时间:2023-12-04 08:45:52 26 4
gpt4 key购买 nike

我只是想在两个日期之间过滤我的记录。
假设有一个记录表 Measurements具有属性 timestamp :

class Measurements(models.Model):
id = models.BigAutoField(primary_key=True)
timestamp = models.DateTimeField()
当我查看 timestamp 时最后一条记录 Measurements.objects.last().timestamp它返回:
datetime.datetime(2020, 10, 13, 6, 29, 48, 90138, tzinfo=<UTC>)
现在我想过滤日期之间的数据 from_dateto_date .根据之前关于这个问题的问题,我使用了 make_aware .为了测试,我使用了 count获取条目的数量。
from .models import *
from datetime import datetime
from django.utils.timezone import make_aware

def get_measurements(request):
from_date = make_aware(datetime(2020, 10, 12, 15, 30, 0, 0))
to_date = make_aware(datetime(2020, 10, 12, 16, 0, 0, 0))
print(from_date)
print(to_date)

measurements = DriveMeasurements.objects.filter(
plc_timestamp__range=["2020-01-01", "2020-01-31"])
print(measurements.count())
在我的 shell 中打印两个日期时,它返回:
datetime.datetime(2020, 10, 12, 15, 30, tzinfo=<UTC>)
datetime.datetime(2020, 10, 12, 16, 0, tzinfo=<UTC>)
当我运行上面的函数时,Django 会触发以下消息:
RuntimeWarning:DateTimeField Measurements.timestamp 在时区支持处于事件状态时收到了一个朴素的日期时间 (2020-01-31 00:00:00)。
warnings.warn("DateTimeField %s 收到了一个简单的日期时间 (%s)"

打印声明 print(measurements.count())版画 0但数据库中有 ~ 18000 条记录。
那么为什么过滤器不起作用并且抛出了 Django 消息呢?

最佳答案

您制作 from_date 确实是正确的和 to_date知道,但您没有在 __range 中使用它查看。您应该与:

def get_measurements(request):
from_date = make_aware(datetime(2020, 10, 12, 15, 30, 0, 0))
to_date = make_aware(datetime(2020, 10, 12, 16, 0, 0, 0))
print(from_date)
print(to_date)

measurements = DriveMeasurements.objects.filter(
# use timezone aware datetimes ↓
plc_timestamp__range=(from_date, to_date)
)
print(measurements.count())

关于python - Django:过滤日期之间的数据 | DatetimeField 收到了一个天真的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64334000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com