预防药
您应该首先使用以下方法避免天真的日期时间:
from django.utils import timezone
now = timezone.now()
如果你像我一样,已经有过必须转变的天真时光,请继续阅读!
姜戈 4+:
从 Django 4 开始,如果您使用zoneinfo
for 时区支持 https://docs.djangoproject.com/en/4.0/topics/i18n/timezones/(这是 Django 4 中的默认设置)您无需执行任何操作即可使用make_aware
以避免此错误。这is_dst
make_aware 标志在 Django 4 中已弃用,并将在 Django 5 中删除。
姜戈 1.9 - 3.2:
您可以使用以下方法解决 AmbigouslyTimeError (感谢盖瑟 https://stackoverflow.com/a/37583232/2800876):
from django.utils import timezone
# This uses `settings.TIME_ZONE` unless you call `timezone.activate()`
timezone.make_aware(some_datetime, is_dst=False)
姜戈 1.x - 1.8:
问题是 make_aware 只是调用 timezone.localize,将 None 传递给参数 is_dst:
timezone.localize(value, is_dst=None)
参数 is_dst 专门用于解决这个不明确的时间错误(http://pytz.sourceforge.net/#tzinfo-api http://pytz.sourceforge.net/#tzinfo-api).
解决方案是自己调用 timezone.localize :
get_current_timezone().localize(some_datetime, is_dst=False)
is_dst=False 将其设置为两个可能时间中的第一个。 is_dst=True 将是第二个。