【问题标题】:Django filter "less than" datetime not working correctlyDjango 过滤器“小于”日期时间无法正常工作
【发布时间】:2019-08-05 21:52:40
【问题描述】:

我正在尝试按时间戳(小于某个值)过滤 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 的 timezone.now() 而不是 datetime.utcnow() 看看它是否能解决问题。
  • last_updated__lt=time_threshold.date() 应该可以解决您的问题

标签: python django datetime filter django-queryset


【解决方案1】:

使用 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()))

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2014-07-01
    • 2013-09-15
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多