Skip to content

Commit 7914f55

Browse files
committed
Checks for tz/tzinfo validity in Timestamp.__new__
closes pandas-dev#17690 possibly pandas-dev#5168
1 parent 058da72 commit 7914f55

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

pandas/_libs/tslib.pyx

+18-1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ from util cimport (is_integer_object, is_float_object, is_datetime64_object,
3030
is_timedelta64_object, INT64_MAX)
3131
cimport util
3232

33+
from cpython.datetime cimport PyTZInfo_Check
3334
# this is our datetime.pxd
3435
from datetime cimport (
3536
pandas_datetimestruct,
@@ -68,7 +69,7 @@ from .tslibs.parsing import parse_datetime_string
6869

6970
cimport cython
7071

71-
from pandas.compat import iteritems, callable
72+
from pandas.compat import iteritems
7273

7374
import collections
7475
import warnings
@@ -373,8 +374,24 @@ class Timestamp(_Timestamp):
373374
FutureWarning)
374375
freq = offset
375376

377+
if tzinfo is not None:
378+
if not PyTZInfo_Check(tzinfo):
379+
# tzinfo must be a datetime.tzinfo object, GH#17690
380+
raise TypeError('tzinfo must be a datetime.tzinfo object, '
381+
'not %s' % type(tzinfo))
382+
elif tz is not None:
383+
raise ValueError('Can provide at most one of tz, tzinfo')
384+
elif ts_input is not _no_input:
385+
raise ValueError('When creating a Timestamp with this type '
386+
'of inputs, the `tzfinfo` argument is '
387+
'ignored. Use `tz` instead.')
388+
376389
if ts_input is _no_input:
377390
# User passed keyword arguments.
391+
if tz is not None:
392+
raise ValueError('When creating a Timestamp from component '
393+
'elements, the `tz` argument is ignored. '
394+
'Use `tzinfo` instead.')
378395
return Timestamp(datetime(year, month, day, hour or 0,
379396
minute or 0, second or 0,
380397
microsecond or 0, tzinfo),

pandas/tests/scalar/test_timestamp.py

+15
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,21 @@ def test_constructor_invalid(self):
175175
with tm.assert_raises_regex(ValueError, 'Cannot convert Period'):
176176
Timestamp(Period('1000-01-01'))
177177

178+
def test_constructor_invalid_tz(self):
179+
# GH#17690, GH#5168
180+
with tm.assert_raises_regex(TypeError, 'must be a datetime.tzinfo'):
181+
Timestamp('2017-10-22', tzinfo='US/Eastern')
182+
183+
with tm.assert_raises_regex(TypeError, 'at most one of'):
184+
Timestamp('2017-10-22', tzinfo=utc, tz='UTC')
185+
186+
with tm.assert_raises_regex(TypeError, 'Use `tzinfo` instead'):
187+
Timestamp(year=2017, month=10, day=22, tz='UTC')
188+
189+
with tm.assert_raises_regex(TypeError, 'Use `tz` instead'):
190+
dt = datetime(2017, 10, 22)
191+
Timestamp(dt, tzinfo=utc)
192+
178193
def test_constructor_positional(self):
179194
# see gh-10758
180195
with pytest.raises(TypeError):

0 commit comments

Comments
 (0)