6

我有一个DateTimeField

class Assignment (models.Model):
   official_deadline = models.DateTimeField(null=True, blank=True)

我需要将它与当前日期时间进行比较,我已经尝试过:

def official_deadline_past(self):
    if datetime.datetime.today() > self.official_deadline:
        return True
    return False

但它总是返回False我也尝试过:

def official_deadline_past(self):
    if datetime.datetime.now() > self.official_deadline:
        return True
    return False

但我有同样的问题。

我在该字段中有一个信息:2011-07-02 00:00:00例如在生成的表单中ModelForm

4

2 回答 2

0

我有同样的问题,django模型日期时间字段只包含日期(没有时间)

now = datetime.datetime.now()

q1=Q()
q1.children.append(Q(datetimefieldFrom__lte=now))
q1.children.append(Q(datetimefieldTo__gte=now))

前任。现在:“2020-12-11 17:17:58.000000” datetimeFrom :“2020-12-11 16:17:58.000000” datetimeFrom :“2020-12-11 18:17:58.000000”

它只是通过“2020-12-11 00:00:00.000000”进行比较

@johnjamesmiller,您的时区问题可以通过修改 setting.py 来解决

TIME_ZONE = 'Asia/Hong_Kong'

USE_TZ = True
于 2020-12-11T08:53:44.357 回答
0

我在 python 2.7.3 和 django 1.3.1 下比较 DateTimeField 和 datetime 时遇到了类似的问题

我认为 DateTimeField 当时没有很好的时区支持,或者我没有正确配置它。

每当我为 datetime 字段指定时区时,我对 DateTimeField > datetime 的所有比较都会失败。

datetime 使用本地中央时间,而 DateTimeField 输入为东部时间。

我最终只是做了一个愚蠢的黑客攻击,将 timedelta(hours=1) 添加到 datetime 中心对象以将其“转换”为东部。

于 2015-12-19T19:35:10.660 回答