小编典典

无法比较天真和有意识的 datetime.now() <= challenge.datetime_end

all

我正在尝试使用比较运算符将当前日期和时间与模型中指定的日期和时间进行比较:

if challenge.datetime_start <= datetime.now() <= challenge.datetime_end:

脚本错误:

TypeError: can't compare offset-naive and offset-aware datetimes

模型如下所示:

class Fundraising_Challenge(models.Model):
    name = models.CharField(max_length=100)
    datetime_start = models.DateTimeField()
    datetime_end = models.DateTimeField()

我也有使用语言环境日期和时间的 django。

我找不到的是 django 用于 DateTimeField() 的格式。是天真还是有意识?以及如何让 datetime.now() 识别语言环境日期时间?


阅读 148

收藏
2022-05-16

共1个答案

小编典典

默认情况下,该datetime对象naive在 Python
中,因此您需要将它们都设为天真的对象或感知datetime对象。这可以使用以下方法完成:

import datetime
import pytz

utc=pytz.UTC

challenge.datetime_start = utc.localize(challenge.datetime_start) 
challenge.datetime_end = utc.localize(challenge.datetime_end) 
# now both the datetime objects are aware, and you can compare them

注意:这会引发一个ValueErroriftzinfo已设置。如果您不确定,请使用

start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)

顺便说一句,您可以使用时区信息在 datetime.datetime 对象中格式化 UNIX 时间戳,如下所示

d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
    year=d.year,
    month=d.month,
    day=d.day,
    hour=d.hour,
    minute=d.minute,
    second=d.second,
    tzinfo=pytz.UTC)
2022-05-16