Skip to content

Commit 9fa063e

Browse files
mroeschkejreback
authored andcommitted
BUG: to_datetime(Timestamp, utc=True) localizes to UTC (#24441)
1 parent 1d86861 commit 9fa063e

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

doc/source/whatsnew/v0.24.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1368,6 +1368,7 @@ Timezones
13681368
- Bug in :meth:`DatetimeIndex.tz_localize` and :meth:`Timestamp.tz_localize` with ``dateutil.tz.tzlocal`` near a DST transition that would return an incorrectly localized datetime (:issue:`23807`)
13691369
- Bug in :class:`Timestamp` constructor where a ``dateutil.tz.tzutc`` timezone passed with a ``datetime.datetime`` argument would be converted to a ``pytz.UTC`` timezone (:issue:`23807`)
13701370
- Bug in :func:`to_datetime` where ``utc=True`` was not respected when specifying a ``unit`` and ``errors='ignore'`` (:issue:`23758`)
1371+
- Bug in :func:`to_datetime` where ``utc=True`` was not respected when passing a :class:`Timestamp` (:issue:`24415`)
13711372

13721373
Offsets
13731374
^^^^^^^

pandas/core/tools/datetimes.py

+5
Original file line numberDiff line numberDiff line change
@@ -568,6 +568,11 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,
568568

569569
if isinstance(arg, Timestamp):
570570
result = arg
571+
if tz is not None:
572+
if arg.tz is not None:
573+
result = result.tz_convert(tz)
574+
else:
575+
result = result.tz_localize(tz)
571576
elif isinstance(arg, ABCSeries):
572577
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
573578
if not cache_array.empty:

pandas/tests/indexes/datetimes/test_tools.py

+10
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,16 @@ def test_non_iso_strings_with_tz_offset(self):
655655
tzinfo=pytz.FixedOffset(240))] * 2)
656656
tm.assert_index_equal(result, expected)
657657

658+
@pytest.mark.parametrize('ts, expected', [
659+
(Timestamp('2018-01-01'),
660+
Timestamp('2018-01-01', tz='UTC')),
661+
(Timestamp('2018-01-01', tz='US/Pacific'),
662+
Timestamp('2018-01-01 08:00', tz='UTC'))])
663+
def test_timestamp_utc_true(self, ts, expected):
664+
# GH 24415
665+
result = to_datetime(ts, utc=True)
666+
assert result == expected
667+
658668

659669
class TestToDatetimeUnit(object):
660670
@pytest.mark.parametrize('cache', [True, False])

0 commit comments

Comments
 (0)