8

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.

Paul
  • 10,381
  • 13
  • 48
  • 86
user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

8

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Mine is 2006. It's is really old. I downloaded it two days ago here: http://sourceforge.net/projects/pytz/ That seemed like a place that would have the updated one. I'll look around for the newer one. – user984003 Nov 13 '12 at 18:09
  • 3
    Download it from http://pypi.python.org/pypi/pytz/ (the Python package index) instead. – Martijn Pieters Nov 13 '12 at 18:10
  • Not sure this should be the accepted answer. It may help for some, but my version is 2017.2 and I'm getting this on `pytz.exceptions.AmbiguousTimeError: 2015-11-01 01:10:07` – shacker May 26 '17 at 07:30
  • 4
    @shacker: but that **is** an ambiguous time. In November the clocks go *back* and `1:10:07` occurs **twice**. That timestamp does *exist*, but it exists both at summer time (DST=1) and at standard time (DST=0). – Martijn Pieters May 26 '17 at 07:35