Python pytz:不存在的时间会引发AmbiguousTimeError而不是NonExistentTimeError。

8

如何判断本地时间是否不存在?我正在尝试使用pytz,但它会抛出AmbiguousTimeError而不是NonExistentTimeError。

由于夏令时的原因,2013年3月31日02:30在哥本哈根永远不会发生。

local_tz = timezone('Europe/Copenhagen')
try:
    non_e = local_tz.localize(datetime.datetime(2013, 3, 31, 2, 30), is_dst = None) 
except pytz.AmbiguousTimeError:
    print "AmbiguousTimeError"

它会跳转到异常处理程序。我尝试过以下方法:
 except pytz.NonExistentTimeError: #'module' object has no attribute 'NonExistentTimeError'
 except pytz.exceptions.NonExistentTimeError: #'module' object has no attribute 'exceptions'

用户通过表单向我提供日期和时间。 这些是本地时间,我需要查看日期和时间是否正确。
我正在使用启用了 USE_TZ = True 的Django,但我认为这在此处并不重要。

这是pytz模块的哪个版本?我确实有NonExistentTimeError异常。 - Martijn Pieters
版本2006p。你的是什么? - user984003
我从其他答案中看到我的版本真的很旧。我两天前在这里下载了它:http://sourceforge.net/projects/pytz/ 我会找一下更新的版本。 - user984003
如我的回答所列:2012d。你落后了6年。:-P - Martijn Pieters
文档 指向 PyPI - Martijn Pieters
1个回答

8

升级您的pytz包。例如,对我而言,在版本2012d中有效:

>>> import pytz, datetime
>>> pytz.__version__
'2012d'
>>> local_tz = pytz.timezone('Europe/Copenhagen')
>>> local_tz.localize(datetime.datetime(2013, 3, 31, 2, 30), is_dst=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pytz/tzinfo.py", line 327, in localize
    raise NonExistentTimeError(dt)
pytz.exceptions.NonExistentTimeError: 2013-03-31 02:30:00

使用 pip install -U pytzeasy_install -U pytz 来升级。

我的是2006年版本,真的很老了。我两天前在 http://sourceforge.net/projects/pytz/ 下载了它,那似乎是个可以有更新版本的地方。我会继续找更新的版本。 - user984003
3
请从 http://pypi.python.org/pypi/pytz/ (Python软件包索引)下载它。 - Martijn Pieters
不确定这是否应该是被接受的答案。它可能对某些人有帮助,但我的版本是2017.2,我正在遇到此问题:pytz.exceptions.AmbiguousTimeError: 2015-11-01 01:10:07 - shacker
5
@shacker: 但那确实是一个模棱两可的时间。在十一月时钟会往回拨,1:10:07这个时间戳会出现两次。这个时间戳存在,但它同时存在于夏令时(DST=1)和标准时间(DST=0)。 - Martijn Pieters

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接