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

新手上路,请多包涵

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

 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() 识别语言环境日期时间?

原文由 sccrthlt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 404
2 个回答

默认情况下, 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

注意:如果 tzinfo 已经设置,这将引发 ValueError 。如果您不确定,请使用

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)

原文由 Viren Rajput 发布,翻译遵循 CC BY-SA 3.0 许可协议

datetime.datetime.now 不知道时区。

Django 为此提供了一个帮助器,它需要 pytz

 from django.utils import timezone
now = timezone.now()

您应该能够将 nowchallenge.datetime_start 进行比较

原文由 Alfredo Aguirre 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题