Skip to content

Commit 9b821e5

Browse files
committed
ENH: prohibit invalid kwargs being passed with a date string
1 parent 5ddc6fb commit 9b821e5

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

pandas/_libs/tslibs/timestamps.pyx

+11-5
Original file line numberDiff line numberDiff line change
@@ -1563,11 +1563,17 @@ class Timestamp(_Timestamp):
15631563
"hour" in kwargs or "minute" in kwargs or "second" in kwargs or
15641564
"microsecond" in kwargs):
15651565
raise ValueError("Cannot pass a date attribute keyword argument")
1566-
if isinstance(args[0], str) and "nanosecond" in kwargs:
1567-
raise ValueError(
1568-
"Cannot pass a date attribute keyword "
1569-
"argument when passing a date string; 'tz' is keyword-only"
1570-
)
1566+
if isinstance(args[0], str):
1567+
if "nanosecond" in kwargs:
1568+
raise ValueError(
1569+
"Cannot pass a date attribute keyword "
1570+
"argument when passing a date string; 'tz' is keyword-only"
1571+
)
1572+
if any(k not in ["tz", "tzinfo", "unit"] for k in kwargs.keys()):
1573+
raise ValueError(
1574+
"When passing a date string "
1575+
"can only pass unit and tz or tzinfo as a keyword argument."
1576+
)
15711577

15721578
ts_input = args[0]
15731579
tzinfo = kwargs.get("tzinfo")

pandas/tests/scalar/timestamp/test_constructors.py

+11
Original file line numberDiff line numberDiff line change
@@ -898,3 +898,14 @@ def test_timestamp_constructor_arg_shift():
898898
result = Timestamp(2019, 10, 27, minute=30)
899899
expected = Timestamp(2019, 10, 27, 0, 30)
900900
assert result == expected
901+
902+
903+
def test_timestamp_constructor_str_invalid_kwargs():
904+
# Check that we didn't pass anything except
905+
# tz, tzinfo, unit with a string
906+
msg = (
907+
"When passing a date string "
908+
"can only pass unit and tz or tzinfo as a keyword argument."
909+
)
910+
with pytest.raises(ValueError, match=msg):
911+
Timestamp("2020-01-01", foo="bar")

0 commit comments

Comments
 (0)