Skip to content

Backport PR #27733 on branch 0.25.x (BUG: fix to_datetime(dti, utc=True)) #27763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Categorical

Datetimelike
^^^^^^^^^^^^

- 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`)
-
-
-
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,9 @@ def _convert_listlike_datetimes(
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
pass
elif tz:
# DatetimeArray, DatetimeIndex
return arg.tz_localize(tz)

return arg

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexes/datetimes/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1620,6 +1620,18 @@ def test_dayfirst(self, cache):
tm.assert_index_equal(expected, idx5)
tm.assert_index_equal(expected, idx6)

@pytest.mark.parametrize("klass", [DatetimeIndex, DatetimeArray])
def test_to_datetime_dta_tz(self, klass):
# GH#27733
dti = date_range("2015-04-05", periods=3).rename("foo")
expected = dti.tz_localize("UTC")

obj = klass(dti)
expected = klass(expected)

result = to_datetime(obj, utc=True)
tm.assert_equal(result, expected)


class TestGuessDatetimeFormat:
@td.skip_if_not_us_locale
Expand Down