我有一个代码如下:
from django.utils.timezone import get_current_timezone, make_aware make_aware(some_datetime, get_current_timezone())
该make_aware
呼叫偶尔引发
AmbiguousTimeError: 2013-11-03 01:23:17
我从Django文档中了解到这是一个夏令时问题,而且这个时间戳实际上是模棱两可的.现在我该如何解决它(比如这可能是两个可能的第一个)?
您应该首先使用以下内容避免天真的日期时间:
from django.utils import timezone now = timezone.now()
如果像我一样,你已经有天真的时间,你必须转换,继续阅读!
您可以使用以下方法解决AmbiguousTimeError(感谢GeyseR):
make_aware(some_datetime, get_current_timezone(), is_dst=False)
问题是make_aware只调用timezone.localize,将None传递给参数is_dst:
timezone.localize(value, is_dst=None)
参数is_dst具体用于解决这种模糊的时间错误(http://pytz.sourceforge.net/#tzinfo-api).
解决方案是自己调用timezone.localize:
get_current_timezone().localize(some_datetime, is_dst=False)
将is_dst = False设置为两次可能的第一次.is_dst = True将是第二个.