From c4f20bdb1168cd4fdd1e527eac33e42667182531 Mon Sep 17 00:00:00 2001 From: deponovo <45828280+deponovo@users.noreply.github.com> Date: Sat, 8 Jan 2022 22:41:08 +0100 Subject: [PATCH] Backport PR #45227: BUG: raise on wrong keyword arguments in Timedelta --- doc/source/whatsnew/v1.4.0.rst | 2 +- pandas/_libs/tslibs/timedeltas.pyx | 5 ++++- pandas/tests/tslibs/test_timedeltas.py | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 12bd51cba47a3..5dd6fa0d4f72d 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -734,7 +734,7 @@ Timedelta ^^^^^^^^^ - Bug in division of all-``NaT`` :class:`TimeDeltaIndex`, :class:`Series` or :class:`DataFrame` column with object-dtype arraylike of numbers failing to infer the result as timedelta64-dtype (:issue:`39750`) - Bug in floor division of ``timedelta64[ns]`` data with a scalar returning garbage values (:issue:`44466`) -- Bug in :class:`Timedelta` now properly taking into account any nanoseconds contribution of any kwarg (:issue:`43764`) +- Bug in :class:`Timedelta` now properly taking into account any nanoseconds contribution of any kwarg (:issue:`43764`, :issue:`45227`) Timezones ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 51624dfb3e17d..d327ca6256015 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1289,7 +1289,10 @@ class Timedelta(_Timedelta): "(days,seconds....)") kwargs = {key: _to_py_int_float(kwargs[key]) for key in kwargs} - if not cls._req_any_kwargs_new.intersection(kwargs): + + unsupported_kwargs = set(kwargs) + unsupported_kwargs.difference_update(cls._req_any_kwargs_new) + if unsupported_kwargs or not cls._req_any_kwargs_new.intersection(kwargs): raise ValueError( "cannot construct a Timedelta from the passed arguments, " "allowed keywords are " diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py index c72d279580cca..a25f148131ea0 100644 --- a/pandas/tests/tslibs/test_timedeltas.py +++ b/pandas/tests/tslibs/test_timedeltas.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -46,3 +48,18 @@ def test_huge_nanoseconds_overflow(): # GH 32402 assert delta_to_nanoseconds(Timedelta(1e10)) == 1e10 assert delta_to_nanoseconds(Timedelta(nanoseconds=1e10)) == 1e10 + + +@pytest.mark.parametrize( + "kwargs", [{"Seconds": 1}, {"seconds": 1, "Nanoseconds": 1}, {"Foo": 2}] +) +def test_kwarg_assertion(kwargs): + err_message = ( + "cannot construct a Timedelta from the passed arguments, " + "allowed keywords are " + "[weeks, days, hours, minutes, seconds, " + "milliseconds, microseconds, nanoseconds]" + ) + + with pytest.raises(ValueError, match=re.escape(err_message)): + Timedelta(**kwargs)