gpt4 book ai didi

python - Django 过滤器 "less than"日期时间无法正常工作

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

我正在尝试按时间戳(小于某个值)过滤 Django 查询集。但是,过滤器似乎允许通过不小于指定时间戳的记录。这是一个示例函数:

def check_jobs_status_3():
current_time = datetime.utcnow()
time_threshold = current_time - timedelta(seconds=60)
print("$$$$$$$$$$$$ current_time = {}, timedelta = {}, time_threshold = {}".format(current_time,timedelta(seconds=60),time_threshold))
stuck_jobs_qs = Job.objects.filter(last_updated__lt=time_threshold)
for stuck_job in stuck_jobs_qs:
print("############################## Job #{} (last_updated = {}) no encoding status after {} seconds. Re-enqueueing.".format(stuck_job.id,stuck_job.last_updated,get_video_encoding_timeout_seconds()))

这是输出:

$$$$$$$$$$$$ current_time = 2019-03-14 20:54:15.221554, timedelta = 0:01:00, time_threshold = 2019-03-14 20:53:15.221554
############################## Job #20 (last_updated = 2019-03-14 20:54:15.221264+00:00) no encoding status after 60 seconds. Re-enqueueing.

如您所见,我收到了一条last_updated设置为2019-03-14 20:54:15的记录,该记录不小于2019-03-14 20:53:15的过滤器值

这是last_updated字段的定义:

last_updated = models.DateTimeField(auto_now=True)

问题可能是什么?

最佳答案

使用 Django 的时区感知方法 django.utils.timezone.now .

from django.utils import timezone

# ...

def check_jobs_status_3():
current_time = timezone.now() # change this
time_threshold = current_time - timedelta(seconds=60)
print("$$$$$$$$$$$$ current_time = {}, timedelta = {}, time_threshold = {}".format(current_time,timedelta(seconds=60),time_threshold))
stuck_jobs_qs = Job.objects.filter(last_updated__lt=time_threshold)
for stuck_job in stuck_jobs_qs:
print("############################## Job #{} (last_updated = {}) no encoding status after {} seconds. Re-enqueueing.".format(stuck_job.id,stuck_job.last_updated,get_video_encoding_timeout_seconds()))

关于python - Django 过滤器 "less than"日期时间无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172069/

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