From 51dc546ac5ffb9175c6e2cd44dbd5399416614b2 Mon Sep 17 00:00:00 2001 From: Brock Date: Fri, 10 Feb 2023 17:25:48 -0800 Subject: [PATCH] BUG: to_datetime with both origin and unit --- doc/source/whatsnew/v2.0.0.rst | 1 + pandas/core/tools/datetimes.py | 2 +- pandas/tests/tools/test_to_datetime.py | 10 ++++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 43a34c8e18b2d..492b209270be1 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1182,6 +1182,7 @@ Datetimelike - Bug in :func:`to_datetime` was not returning input with ``errors='ignore'`` when input was out-of-bounds (:issue:`50587`) - Bug in :func:`DataFrame.from_records` when given a :class:`DataFrame` input with timezone-aware datetime64 columns incorrectly dropping the timezone-awareness (:issue:`51162`) - Bug in :func:`to_datetime` was raising ``decimal.InvalidOperation`` when parsing date strings with ``errors='coerce'`` (:issue:`51084`) +- Bug in :func:`to_datetime` with both ``unit`` and ``origin`` specified returning incorrect results (:issue:`42624`) - Timedelta diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 76e144c70c7d5..3006bc6290ff7 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -606,7 +606,7 @@ def _adjust_to_origin(arg, origin, unit): # we are going to offset back to unix / epoch time try: - offset = Timestamp(origin) + offset = Timestamp(origin, unit=unit) except OutOfBoundsDatetime as err: raise OutOfBoundsDatetime(f"origin {origin} is Out of Bounds") from err except ValueError as err: diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index ef5ace2d1f1ed..31b9f2f991efd 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -3196,6 +3196,16 @@ def julian_dates(): class TestOrigin: + def test_origin_and_unit(self): + # GH#42624 + ts = to_datetime(1, unit="s", origin=1) + expected = Timestamp("1970-01-01 00:00:02") + assert ts == expected + + ts = to_datetime(1, unit="s", origin=1_000_000_000) + expected = Timestamp("2001-09-09 01:46:41") + assert ts == expected + def test_julian(self, julian_dates): # gh-11276, gh-11745 # for origin as julian