Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pytz: non-existent time gets AmbiguousTimeError, not NonExistentTimeError

How can I tell if a local time is non-existent? I'm trying with pytz, but it throws an AmbiguousTimeError, not a NonExistentTimeError.

2013-3-31 02:30 will never happen in Copenhagen due to daylight savings time.

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"

It goes to the exception handler. I've tried:

 except pytz.NonExistentTimeError: #'module' object has no attribute 'NonExistentTimeError'
 except pytz.exceptions.NonExistentTimeError: #'module' object has no attribute 'exceptions'

The user supplies me with a date and time via a form. These are in local time and I need to see whether the dates and times are ok.

I'm using Django with USE_TZ = True, but I don't think that matters here.

like image 214
user984003 Avatar asked Nov 13 '12 17:11

user984003


1 Answers

Upgrade your pytz package. This works for me in version 2012d for example:

>>> 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

Use pip install -U pytz or easy_install -U pytz to upgrade.

like image 146
Martijn Pieters Avatar answered Oct 21 '22 11:10

Martijn Pieters