diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index d12d929470be5..df6c131489726 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1368,6 +1368,7 @@ Timezones - 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`) - 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`) - Bug in :func:`to_datetime` where ``utc=True`` was not respected when specifying a ``unit`` and ``errors='ignore'`` (:issue:`23758`) +- Bug in :func:`to_datetime` where ``utc=True`` was not respected when passing a :class:`Timestamp` (:issue:`24415`) Offsets ^^^^^^^ diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 4df6f4c661d43..69d735d7fdc65 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -568,6 +568,11 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, if isinstance(arg, Timestamp): result = arg + if tz is not None: + if arg.tz is not None: + result = result.tz_convert(tz) + else: + result = result.tz_localize(tz) elif isinstance(arg, ABCSeries): cache_array = _maybe_cache(arg, format, cache, convert_listlike) if not cache_array.empty: diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 0abcf597f7212..530da1a625af4 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -655,6 +655,16 @@ def test_non_iso_strings_with_tz_offset(self): tzinfo=pytz.FixedOffset(240))] * 2) tm.assert_index_equal(result, expected) + @pytest.mark.parametrize('ts, expected', [ + (Timestamp('2018-01-01'), + Timestamp('2018-01-01', tz='UTC')), + (Timestamp('2018-01-01', tz='US/Pacific'), + Timestamp('2018-01-01 08:00', tz='UTC'))]) + def test_timestamp_utc_true(self, ts, expected): + # GH 24415 + result = to_datetime(ts, utc=True) + assert result == expected + class TestToDatetimeUnit(object): @pytest.mark.parametrize('cache', [True, False])