如何解决无法比较原始日期时间和感知日期时间now<=challenge.datetime\u end
默认情况下,该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
注意:这将引发一个ValueErrorif tzinfo
值。如果你不确定,请使用
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)
解决方法
我正在尝试使用比较运算符将当前日期和时间与模型中指定的日期和时间进行比较:
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()来识别语言环境datetime?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。