Skip to content

Commit 9c0ebd8

Browse files
committed
BUG: Correctly localize naive ts strings with Series and datetimetz dtype (pandas-dev#17415)
1 parent 21a3800 commit 9c0ebd8

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

pandas/core/dtypes/cast.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
is_integer_dtype,
1919
is_datetime_or_timedelta_dtype,
2020
is_bool_dtype, is_scalar,
21-
_string_dtypes,
21+
is_string_dtype, _string_dtypes,
2222
pandas_dtype,
2323
_ensure_int8, _ensure_int16,
2424
_ensure_int32, _ensure_int64,
@@ -965,12 +965,16 @@ def maybe_cast_to_datetime(value, dtype, errors='raise'):
965965
if is_datetime64:
966966
value = to_datetime(value, errors=errors)._values
967967
elif is_datetime64tz:
968-
# input has to be UTC at this point, so just
969-
# localize
970-
value = (to_datetime(value, errors=errors)
971-
.tz_localize('UTC')
972-
.tz_convert(dtype.tz)
973-
)
968+
is_dt_string = is_string_dtype(value)
969+
value = to_datetime(value, errors=errors)
970+
if is_dt_string:
971+
# Strings here are naive, so directly localize
972+
value = value.tz_localize(dtype.tz)
973+
else:
974+
# Numeric values are UTC at this point,
975+
# so localize and convert
976+
value = (value.tz_localize('UTC')
977+
.tz_convert(dtype.tz))
974978
elif is_timedelta64:
975979
value = to_timedelta(value, errors=errors)._values
976980
except (AttributeError, ValueError, TypeError):

pandas/tests/series/test_constructors.py

+6
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,12 @@ def test_constructor_with_datetime_tz(self):
553553
expected = Series(pd.DatetimeIndex(['NaT', 'NaT'], tz='US/Eastern'))
554554
assert_series_equal(s, expected)
555555

556+
# GH 17415: With naive string
557+
ts_naive = '2013-01-01 00:00:00'
558+
result = Series([ts_naive], dtype='datetime64[ns, CET]')
559+
expected = Series([pd.Timestamp(ts_naive, tz='CET')])
560+
assert_series_equal(result, expected)
561+
556562
def test_construction_interval(self):
557563
# construction from interval & array of intervals
558564
index = IntervalIndex.from_breaks(np.arange(3), closed='right')

0 commit comments

Comments
 (0)