Skip to content

Commit 61819ab

Browse files
jbrockmendelmroeschke
authored andcommitted
BUG: fix to_datetime(dti, utc=True) (#27733)
* BUG: fix to_datetime(dti, utc=True) * whatsnew, suggested edits * parametrize * backquotes
1 parent ac69333 commit 61819ab

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v0.25.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ Categorical
3131

3232
Datetimelike
3333
^^^^^^^^^^^^
34-
34+
- Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`)
3535
-
3636
-
3737
-

pandas/core/tools/datetimes.py

+3
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,9 @@ def _convert_listlike_datetimes(
334334
return DatetimeIndex(arg, tz=tz, name=name)
335335
except ValueError:
336336
pass
337+
elif tz:
338+
# DatetimeArray, DatetimeIndex
339+
return arg.tz_localize(tz)
337340

338341
return arg
339342

pandas/tests/indexes/datetimes/test_tools.py

+12
Original file line numberDiff line numberDiff line change
@@ -1620,6 +1620,18 @@ def test_dayfirst(self, cache):
16201620
tm.assert_index_equal(expected, idx5)
16211621
tm.assert_index_equal(expected, idx6)
16221622

1623+
@pytest.mark.parametrize("klass", [DatetimeIndex, DatetimeArray])
1624+
def test_to_datetime_dta_tz(self, klass):
1625+
# GH#27733
1626+
dti = date_range("2015-04-05", periods=3).rename("foo")
1627+
expected = dti.tz_localize("UTC")
1628+
1629+
obj = klass(dti)
1630+
expected = klass(expected)
1631+
1632+
result = to_datetime(obj, utc=True)
1633+
tm.assert_equal(result, expected)
1634+
16231635

16241636
class TestGuessDatetimeFormat:
16251637
@td.skip_if_not_us_locale

0 commit comments

Comments
 (0)