content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\concat\__pycache__\test_index.cpython-313.pyc
test_index.cpython-313.pyc
Other
25,564
0.8
0
0.003322
vue-tools
861
2025-04-24T14:52:40.912989
GPL-3.0
true
32b979dcde19fe0613737ccb1b51c498
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\concat\__pycache__\test_invalid.cpython-313.pyc
test_invalid.cpython-313.pyc
Other
3,405
0.8
0
0
vue-tools
904
2023-08-27T20:47:03.714191
MIT
true
d54eab933c97b5b4c49ec83736dde331
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\concat\__pycache__\test_series.cpython-313.pyc
test_series.cpython-313.pyc
Other
9,753
0.8
0
0
node-utils
446
2023-10-15T20:38:52.760597
GPL-3.0
true
88422ca060aedb93ea764e098296938e
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\concat\__pycache__\test_sort.cpython-313.pyc
test_sort.cpython-313.pyc
Other
6,476
0.8
0
0
awesome-app
214
2024-10-03T07:43:06.347357
Apache-2.0
true
6fd125ec14a027ffc755c5d27526defa
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\concat\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
python-kit
486
2024-09-11T02:02:35.845170
GPL-3.0
true
c13acec55bd4b742e98bb85a4dcccaf8
import re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._config import using_string_dtype\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Index,\n MultiIndex,\n Series,\n Timestamp,\n bdate_range,\n concat,\n merge,\n option_context,\n)\nimport pandas._testing as tm\n\n\ndef get_test_data(ngroups=8, n=50):\n unique_groups = list(range(ngroups))\n arr = np.asarray(np.tile(unique_groups, n // ngroups))\n\n if len(arr) < n:\n arr = np.asarray(list(arr) + unique_groups[: n - len(arr)])\n\n np.random.default_rng(2).shuffle(arr)\n return arr\n\n\nclass TestJoin:\n # aggregate multiple columns\n @pytest.fixture\n def df(self):\n df = DataFrame(\n {\n "key1": get_test_data(),\n "key2": get_test_data(),\n "data1": np.random.default_rng(2).standard_normal(50),\n "data2": np.random.default_rng(2).standard_normal(50),\n }\n )\n\n # exclude a couple keys for fun\n df = df[df["key2"] > 1]\n return df\n\n @pytest.fixture\n def df2(self):\n return DataFrame(\n {\n "key1": get_test_data(n=10),\n "key2": get_test_data(ngroups=4, n=10),\n "value": np.random.default_rng(2).standard_normal(10),\n }\n )\n\n @pytest.fixture\n def target_source(self):\n data = {\n "A": [0.0, 1.0, 2.0, 3.0, 4.0],\n "B": [0.0, 1.0, 0.0, 1.0, 0.0],\n "C": ["foo1", "foo2", "foo3", "foo4", "foo5"],\n "D": bdate_range("1/1/2009", periods=5),\n }\n target = DataFrame(data, index=Index(["a", "b", "c", "d", "e"], dtype=object))\n\n # Join on string value\n\n source = DataFrame(\n {"MergedA": data["A"], "MergedD": data["D"]}, index=data["C"]\n )\n return target, source\n\n def test_left_outer_join(self, df, df2):\n joined_key2 = merge(df, df2, on="key2")\n _check_join(df, df2, joined_key2, ["key2"], how="left")\n\n joined_both = merge(df, df2)\n _check_join(df, df2, joined_both, ["key1", "key2"], how="left")\n\n def test_right_outer_join(self, df, df2):\n joined_key2 = merge(df, df2, on="key2", how="right")\n _check_join(df, df2, joined_key2, ["key2"], how="right")\n\n joined_both = merge(df, df2, how="right")\n _check_join(df, df2, joined_both, ["key1", "key2"], how="right")\n\n def test_full_outer_join(self, df, df2):\n joined_key2 = merge(df, df2, on="key2", how="outer")\n _check_join(df, df2, joined_key2, ["key2"], how="outer")\n\n joined_both = merge(df, df2, how="outer")\n _check_join(df, df2, joined_both, ["key1", "key2"], how="outer")\n\n def test_inner_join(self, df, df2):\n joined_key2 = merge(df, df2, on="key2", how="inner")\n _check_join(df, df2, joined_key2, ["key2"], how="inner")\n\n joined_both = merge(df, df2, how="inner")\n _check_join(df, df2, joined_both, ["key1", "key2"], how="inner")\n\n def test_handle_overlap(self, df, df2):\n joined = merge(df, df2, on="key2", suffixes=(".foo", ".bar"))\n\n assert "key1.foo" in joined\n assert "key1.bar" in joined\n\n def test_handle_overlap_arbitrary_key(self, df, df2):\n joined = merge(\n df,\n df2,\n left_on="key2",\n right_on="key1",\n suffixes=(".foo", ".bar"),\n )\n assert "key1.foo" in joined\n assert "key2.bar" in joined\n\n @pytest.mark.parametrize(\n "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]\n )\n def test_join_on(self, target_source, infer_string):\n target, source = target_source\n\n merged = target.join(source, on="C")\n tm.assert_series_equal(merged["MergedA"], target["A"], check_names=False)\n tm.assert_series_equal(merged["MergedD"], target["D"], check_names=False)\n\n # join with duplicates (fix regression from DataFrame/Matrix merge)\n df = DataFrame({"key": ["a", "a", "b", "b", "c"]})\n df2 = DataFrame({"value": [0, 1, 2]}, index=["a", "b", "c"])\n joined = df.join(df2, on="key")\n expected = DataFrame(\n {"key": ["a", "a", "b", "b", "c"], "value": [0, 0, 1, 1, 2]}\n )\n tm.assert_frame_equal(joined, expected)\n\n # Test when some are missing\n df_a = DataFrame([[1], [2], [3]], index=["a", "b", "c"], columns=["one"])\n df_b = DataFrame([["foo"], ["bar"]], index=[1, 2], columns=["two"])\n df_c = DataFrame([[1], [2]], index=[1, 2], columns=["three"])\n joined = df_a.join(df_b, on="one")\n joined = joined.join(df_c, on="one")\n assert np.isnan(joined["two"]["c"])\n assert np.isnan(joined["three"]["c"])\n\n # merge column not p resent\n with pytest.raises(KeyError, match="^'E'$"):\n target.join(source, on="E")\n\n # overlap\n source_copy = source.copy()\n msg = (\n "You are trying to merge on float64 and object|str columns for key "\n "'A'. If you wish to proceed you should use pd.concat"\n )\n with pytest.raises(ValueError, match=msg):\n target.join(source_copy, on="A")\n\n def test_join_on_fails_with_different_right_index(self):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=3),\n "b": np.random.default_rng(2).standard_normal(3),\n }\n )\n df2 = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=10),\n "b": np.random.default_rng(2).standard_normal(10),\n },\n index=MultiIndex.from_product([range(5), ["A", "B"]]),\n )\n msg = r'len\(left_on\) must equal the number of levels in the index of "right"'\n with pytest.raises(ValueError, match=msg):\n merge(df, df2, left_on="a", right_index=True)\n\n def test_join_on_fails_with_different_left_index(self):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=3),\n "b": np.random.default_rng(2).standard_normal(3),\n },\n index=MultiIndex.from_arrays([range(3), list("abc")]),\n )\n df2 = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=10),\n "b": np.random.default_rng(2).standard_normal(10),\n }\n )\n msg = r'len\(right_on\) must equal the number of levels in the index of "left"'\n with pytest.raises(ValueError, match=msg):\n merge(df, df2, right_on="b", left_index=True)\n\n def test_join_on_fails_with_different_column_counts(self):\n df = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=3),\n "b": np.random.default_rng(2).standard_normal(3),\n }\n )\n df2 = DataFrame(\n {\n "a": np.random.default_rng(2).choice(["m", "f"], size=10),\n "b": np.random.default_rng(2).standard_normal(10),\n },\n index=MultiIndex.from_product([range(5), ["A", "B"]]),\n )\n msg = r"len\(right_on\) must equal len\(left_on\)"\n with pytest.raises(ValueError, match=msg):\n merge(df, df2, right_on="a", left_on=["a", "b"])\n\n @pytest.mark.parametrize("wrong_type", [2, "str", None, np.array([0, 1])])\n def test_join_on_fails_with_wrong_object_type(self, wrong_type):\n # GH12081 - original issue\n\n # GH21220 - merging of Series and DataFrame is now allowed\n # Edited test to remove the Series object from test parameters\n\n df = DataFrame({"a": [1, 1]})\n msg = (\n "Can only merge Series or DataFrame objects, "\n f"a {type(wrong_type)} was passed"\n )\n with pytest.raises(TypeError, match=msg):\n merge(wrong_type, df, left_on="a", right_on="a")\n with pytest.raises(TypeError, match=msg):\n merge(df, wrong_type, left_on="a", right_on="a")\n\n def test_join_on_pass_vector(self, target_source):\n target, source = target_source\n expected = target.join(source, on="C")\n expected = expected.rename(columns={"C": "key_0"})\n expected = expected[["key_0", "A", "B", "D", "MergedA", "MergedD"]]\n\n join_col = target.pop("C")\n result = target.join(source, on=join_col)\n tm.assert_frame_equal(result, expected)\n\n def test_join_with_len0(self, target_source):\n # nothing to merge\n target, source = target_source\n merged = target.join(source.reindex([]), on="C")\n for col in source:\n assert col in merged\n assert merged[col].isna().all()\n\n merged2 = target.join(source.reindex([]), on="C", how="inner")\n tm.assert_index_equal(merged2.columns, merged.columns)\n assert len(merged2) == 0\n\n def test_join_on_inner(self):\n df = DataFrame({"key": ["a", "a", "d", "b", "b", "c"]})\n df2 = DataFrame({"value": [0, 1]}, index=["a", "b"])\n\n joined = df.join(df2, on="key", how="inner")\n\n expected = df.join(df2, on="key")\n expected = expected[expected["value"].notna()]\n tm.assert_series_equal(joined["key"], expected["key"])\n tm.assert_series_equal(joined["value"], expected["value"], check_dtype=False)\n tm.assert_index_equal(joined.index, expected.index)\n\n def test_join_on_singlekey_list(self):\n df = DataFrame({"key": ["a", "a", "b", "b", "c"]})\n df2 = DataFrame({"value": [0, 1, 2]}, index=["a", "b", "c"])\n\n # corner cases\n joined = df.join(df2, on=["key"])\n expected = df.join(df2, on="key")\n\n tm.assert_frame_equal(joined, expected)\n\n def test_join_on_series(self, target_source):\n target, source = target_source\n result = target.join(source["MergedA"], on="C")\n expected = target.join(source[["MergedA"]], on="C")\n tm.assert_frame_equal(result, expected)\n\n def test_join_on_series_buglet(self):\n # GH #638\n df = DataFrame({"a": [1, 1]})\n ds = Series([2], index=[1], name="b")\n result = df.join(ds, on="a")\n expected = DataFrame({"a": [1, 1], "b": [2, 2]}, index=df.index)\n tm.assert_frame_equal(result, expected)\n\n def test_join_index_mixed(self, join_type):\n # no overlapping blocks\n df1 = DataFrame(index=np.arange(10))\n df1["bool"] = True\n df1["string"] = "foo"\n\n df2 = DataFrame(index=np.arange(5, 15))\n df2["int"] = 1\n df2["float"] = 1.0\n\n joined = df1.join(df2, how=join_type)\n expected = _join_by_hand(df1, df2, how=join_type)\n tm.assert_frame_equal(joined, expected)\n\n joined = df2.join(df1, how=join_type)\n expected = _join_by_hand(df2, df1, how=join_type)\n tm.assert_frame_equal(joined, expected)\n\n def test_join_index_mixed_overlap(self):\n df1 = DataFrame(\n {"A": 1.0, "B": 2, "C": "foo", "D": True},\n index=np.arange(10),\n columns=["A", "B", "C", "D"],\n )\n assert df1["B"].dtype == np.int64\n assert df1["D"].dtype == np.bool_\n\n df2 = DataFrame(\n {"A": 1.0, "B": 2, "C": "foo", "D": True},\n index=np.arange(0, 10, 2),\n columns=["A", "B", "C", "D"],\n )\n\n # overlap\n joined = df1.join(df2, lsuffix="_one", rsuffix="_two")\n expected_columns = [\n "A_one",\n "B_one",\n "C_one",\n "D_one",\n "A_two",\n "B_two",\n "C_two",\n "D_two",\n ]\n df1.columns = expected_columns[:4]\n df2.columns = expected_columns[4:]\n expected = _join_by_hand(df1, df2)\n tm.assert_frame_equal(joined, expected)\n\n # triggers warning about empty entries\n @pytest.mark.xfail(using_string_dtype(), reason="TODO(infer_string)")\n def test_join_empty_bug(self):\n # generated an exception in 0.4.3\n x = DataFrame()\n x.join(DataFrame([3], index=[0], columns=["A"]), how="outer")\n\n def test_join_unconsolidated(self):\n # GH #331\n a = DataFrame(\n np.random.default_rng(2).standard_normal((30, 2)), columns=["a", "b"]\n )\n c = Series(np.random.default_rng(2).standard_normal(30))\n a["c"] = c\n d = DataFrame(np.random.default_rng(2).standard_normal((30, 1)), columns=["q"])\n\n # it works!\n a.join(d)\n d.join(a)\n\n def test_join_multiindex(self):\n index1 = MultiIndex.from_arrays(\n [["a", "a", "a", "b", "b", "b"], [1, 2, 3, 1, 2, 3]],\n names=["first", "second"],\n )\n\n index2 = MultiIndex.from_arrays(\n [["b", "b", "b", "c", "c", "c"], [1, 2, 3, 1, 2, 3]],\n names=["first", "second"],\n )\n\n df1 = DataFrame(\n data=np.random.default_rng(2).standard_normal(6),\n index=index1,\n columns=["var X"],\n )\n df2 = DataFrame(\n data=np.random.default_rng(2).standard_normal(6),\n index=index2,\n columns=["var Y"],\n )\n\n df1 = df1.sort_index(level=0)\n df2 = df2.sort_index(level=0)\n\n joined = df1.join(df2, how="outer")\n ex_index = Index(index1.values).union(Index(index2.values))\n expected = df1.reindex(ex_index).join(df2.reindex(ex_index))\n expected.index.names = index1.names\n tm.assert_frame_equal(joined, expected)\n assert joined.index.names == index1.names\n\n df1 = df1.sort_index(level=1)\n df2 = df2.sort_index(level=1)\n\n joined = df1.join(df2, how="outer").sort_index(level=0)\n ex_index = Index(index1.values).union(Index(index2.values))\n expected = df1.reindex(ex_index).join(df2.reindex(ex_index))\n expected.index.names = index1.names\n\n tm.assert_frame_equal(joined, expected)\n assert joined.index.names == index1.names\n\n def test_join_inner_multiindex(self, lexsorted_two_level_string_multiindex):\n key1 = ["bar", "bar", "bar", "foo", "foo", "baz", "baz", "qux", "qux", "snap"]\n key2 = [\n "two",\n "one",\n "three",\n "one",\n "two",\n "one",\n "two",\n "two",\n "three",\n "one",\n ]\n\n data = np.random.default_rng(2).standard_normal(len(key1))\n data = DataFrame({"key1": key1, "key2": key2, "data": data})\n\n index = lexsorted_two_level_string_multiindex\n to_join = DataFrame(\n np.random.default_rng(2).standard_normal((10, 3)),\n index=index,\n columns=["j_one", "j_two", "j_three"],\n )\n\n joined = data.join(to_join, on=["key1", "key2"], how="inner")\n expected = merge(\n data,\n to_join.reset_index(),\n left_on=["key1", "key2"],\n right_on=["first", "second"],\n how="inner",\n sort=False,\n )\n\n expected2 = merge(\n to_join,\n data,\n right_on=["key1", "key2"],\n left_index=True,\n how="inner",\n sort=False,\n )\n tm.assert_frame_equal(joined, expected2.reindex_like(joined))\n\n expected2 = merge(\n to_join,\n data,\n right_on=["key1", "key2"],\n left_index=True,\n how="inner",\n sort=False,\n )\n\n expected = expected.drop(["first", "second"], axis=1)\n expected.index = joined.index\n\n assert joined.index.is_monotonic_increasing\n tm.assert_frame_equal(joined, expected)\n\n # _assert_same_contents(expected, expected2.loc[:, expected.columns])\n\n def test_join_hierarchical_mixed_raises(self):\n # GH 2024\n # GH 40993: For raising, enforced in 2.0\n df = DataFrame([(1, 2, 3), (4, 5, 6)], columns=["a", "b", "c"])\n new_df = df.groupby(["a"]).agg({"b": ["mean", "sum"]})\n other_df = DataFrame([(1, 2, 3), (7, 10, 6)], columns=["a", "b", "d"])\n other_df.set_index("a", inplace=True)\n # GH 9455, 12219\n with pytest.raises(\n pd.errors.MergeError, match="Not allowed to merge between different levels"\n ):\n merge(new_df, other_df, left_index=True, right_index=True)\n\n def test_join_float64_float32(self):\n a = DataFrame(\n np.random.default_rng(2).standard_normal((10, 2)),\n columns=["a", "b"],\n dtype=np.float64,\n )\n b = DataFrame(\n np.random.default_rng(2).standard_normal((10, 1)),\n columns=["c"],\n dtype=np.float32,\n )\n joined = a.join(b)\n assert joined.dtypes["a"] == "float64"\n assert joined.dtypes["b"] == "float64"\n assert joined.dtypes["c"] == "float32"\n\n a = np.random.default_rng(2).integers(0, 5, 100).astype("int64")\n b = np.random.default_rng(2).random(100).astype("float64")\n c = np.random.default_rng(2).random(100).astype("float32")\n df = DataFrame({"a": a, "b": b, "c": c})\n xpdf = DataFrame({"a": a, "b": b, "c": c})\n s = DataFrame(\n np.random.default_rng(2).random(5).astype("float32"), columns=["md"]\n )\n rs = df.merge(s, left_on="a", right_index=True)\n assert rs.dtypes["a"] == "int64"\n assert rs.dtypes["b"] == "float64"\n assert rs.dtypes["c"] == "float32"\n assert rs.dtypes["md"] == "float32"\n\n xp = xpdf.merge(s, left_on="a", right_index=True)\n tm.assert_frame_equal(rs, xp)\n\n def test_join_many_non_unique_index(self):\n df1 = DataFrame({"a": [1, 1], "b": [1, 1], "c": [10, 20]})\n df2 = DataFrame({"a": [1, 1], "b": [1, 2], "d": [100, 200]})\n df3 = DataFrame({"a": [1, 1], "b": [1, 2], "e": [1000, 2000]})\n idf1 = df1.set_index(["a", "b"])\n idf2 = df2.set_index(["a", "b"])\n idf3 = df3.set_index(["a", "b"])\n\n result = idf1.join([idf2, idf3], how="outer")\n\n df_partially_merged = merge(df1, df2, on=["a", "b"], how="outer")\n expected = merge(df_partially_merged, df3, on=["a", "b"], how="outer")\n\n result = result.reset_index()\n expected = expected[result.columns]\n expected["a"] = expected.a.astype("int64")\n expected["b"] = expected.b.astype("int64")\n tm.assert_frame_equal(result, expected)\n\n df1 = DataFrame({"a": [1, 1, 1], "b": [1, 1, 1], "c": [10, 20, 30]})\n df2 = DataFrame({"a": [1, 1, 1], "b": [1, 1, 2], "d": [100, 200, 300]})\n df3 = DataFrame({"a": [1, 1, 1], "b": [1, 1, 2], "e": [1000, 2000, 3000]})\n idf1 = df1.set_index(["a", "b"])\n idf2 = df2.set_index(["a", "b"])\n idf3 = df3.set_index(["a", "b"])\n result = idf1.join([idf2, idf3], how="inner")\n\n df_partially_merged = merge(df1, df2, on=["a", "b"], how="inner")\n expected = merge(df_partially_merged, df3, on=["a", "b"], how="inner")\n\n result = result.reset_index()\n\n tm.assert_frame_equal(result, expected.loc[:, result.columns])\n\n # GH 11519\n df = DataFrame(\n {\n "A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],\n "B": ["one", "one", "two", "three", "two", "two", "one", "three"],\n "C": np.random.default_rng(2).standard_normal(8),\n "D": np.random.default_rng(2).standard_normal(8),\n }\n )\n s = Series(\n np.repeat(np.arange(8), 2), index=np.repeat(np.arange(8), 2), name="TEST"\n )\n inner = df.join(s, how="inner")\n outer = df.join(s, how="outer")\n left = df.join(s, how="left")\n right = df.join(s, how="right")\n tm.assert_frame_equal(inner, outer)\n tm.assert_frame_equal(inner, left)\n tm.assert_frame_equal(inner, right)\n\n @pytest.mark.parametrize(\n "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]\n )\n def test_join_sort(self, infer_string):\n with option_context("future.infer_string", infer_string):\n left = DataFrame(\n {"key": ["foo", "bar", "baz", "foo"], "value": [1, 2, 3, 4]}\n )\n right = DataFrame({"value2": ["a", "b", "c"]}, index=["bar", "baz", "foo"])\n\n joined = left.join(right, on="key", sort=True)\n expected = DataFrame(\n {\n "key": ["bar", "baz", "foo", "foo"],\n "value": [2, 3, 1, 4],\n "value2": ["a", "b", "c", "c"],\n },\n index=[1, 2, 0, 3],\n )\n tm.assert_frame_equal(joined, expected)\n\n # smoke test\n joined = left.join(right, on="key", sort=False)\n tm.assert_index_equal(joined.index, Index(range(4)), exact=True)\n\n def test_join_mixed_non_unique_index(self):\n # GH 12814, unorderable types in py3 with a non-unique index\n df1 = DataFrame({"a": [1, 2, 3, 4]}, index=[1, 2, 3, "a"])\n df2 = DataFrame({"b": [5, 6, 7, 8]}, index=[1, 3, 3, 4])\n result = df1.join(df2)\n expected = DataFrame(\n {"a": [1, 2, 3, 3, 4], "b": [5, np.nan, 6, 7, np.nan]},\n index=[1, 2, 3, 3, "a"],\n )\n tm.assert_frame_equal(result, expected)\n\n df3 = DataFrame({"a": [1, 2, 3, 4]}, index=[1, 2, 2, "a"])\n df4 = DataFrame({"b": [5, 6, 7, 8]}, index=[1, 2, 3, 4])\n result = df3.join(df4)\n expected = DataFrame(\n {"a": [1, 2, 3, 4], "b": [5, 6, 6, np.nan]}, index=[1, 2, 2, "a"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_join_non_unique_period_index(self):\n # GH #16871\n index = pd.period_range("2016-01-01", periods=16, freq="M")\n df = DataFrame(list(range(len(index))), index=index, columns=["pnum"])\n df2 = concat([df, df])\n result = df.join(df2, how="inner", rsuffix="_df2")\n expected = DataFrame(\n np.tile(np.arange(16, dtype=np.int64).repeat(2).reshape(-1, 1), 2),\n columns=["pnum", "pnum_df2"],\n index=df2.sort_index().index,\n )\n tm.assert_frame_equal(result, expected)\n\n def test_mixed_type_join_with_suffix(self, using_infer_string):\n # GH #916\n df = DataFrame(\n np.random.default_rng(2).standard_normal((20, 6)),\n columns=["a", "b", "c", "d", "e", "f"],\n )\n df.insert(0, "id", 0)\n df.insert(5, "dt", "foo")\n\n grouped = df.groupby("id")\n msg = re.escape("agg function failed [how->mean,dtype->")\n if using_infer_string:\n msg = "dtype 'str' does not support operation 'mean'"\n with pytest.raises(TypeError, match=msg):\n grouped.mean()\n mn = grouped.mean(numeric_only=True)\n cn = grouped.count()\n\n # it works!\n mn.join(cn, rsuffix="_right")\n\n def test_join_many(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((10, 6)), columns=list("abcdef")\n )\n df_list = [df[["a", "b"]], df[["c", "d"]], df[["e", "f"]]]\n\n joined = df_list[0].join(df_list[1:])\n tm.assert_frame_equal(joined, df)\n\n df_list = [df[["a", "b"]][:-2], df[["c", "d"]][2:], df[["e", "f"]][1:9]]\n\n def _check_diff_index(df_list, result, exp_index):\n reindexed = [x.reindex(exp_index) for x in df_list]\n expected = reindexed[0].join(reindexed[1:])\n tm.assert_frame_equal(result, expected)\n\n # different join types\n joined = df_list[0].join(df_list[1:], how="outer")\n _check_diff_index(df_list, joined, df.index)\n\n joined = df_list[0].join(df_list[1:])\n _check_diff_index(df_list, joined, df_list[0].index)\n\n joined = df_list[0].join(df_list[1:], how="inner")\n _check_diff_index(df_list, joined, df.index[2:8])\n\n msg = "Joining multiple DataFrames only supported for joining on index"\n with pytest.raises(ValueError, match=msg):\n df_list[0].join(df_list[1:], on="a")\n\n def test_join_many_mixed(self):\n df = DataFrame(\n np.random.default_rng(2).standard_normal((8, 4)),\n columns=["A", "B", "C", "D"],\n )\n df["key"] = ["foo", "bar"] * 4\n df1 = df.loc[:, ["A", "B"]]\n df2 = df.loc[:, ["C", "D"]]\n df3 = df.loc[:, ["key"]]\n\n result = df1.join([df2, df3])\n tm.assert_frame_equal(result, df)\n\n def test_join_dups(self):\n # joining dups\n df = concat(\n [\n DataFrame(\n np.random.default_rng(2).standard_normal((10, 4)),\n columns=["A", "A", "B", "B"],\n ),\n DataFrame(\n np.random.default_rng(2).integers(0, 10, size=20).reshape(10, 2),\n columns=["A", "C"],\n ),\n ],\n axis=1,\n )\n\n expected = concat([df, df], axis=1)\n result = df.join(df, rsuffix="_2")\n result.columns = expected.columns\n tm.assert_frame_equal(result, expected)\n\n # GH 4975, invalid join on dups\n w = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)), columns=["x", "y"]\n )\n x = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)), columns=["x", "y"]\n )\n y = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)), columns=["x", "y"]\n )\n z = DataFrame(\n np.random.default_rng(2).standard_normal((4, 2)), columns=["x", "y"]\n )\n\n dta = x.merge(y, left_index=True, right_index=True).merge(\n z, left_index=True, right_index=True, how="outer"\n )\n # GH 40991: As of 2.0 causes duplicate columns\n with pytest.raises(\n pd.errors.MergeError,\n match="Passing 'suffixes' which cause duplicate columns",\n ):\n dta.merge(w, left_index=True, right_index=True)\n\n def test_join_multi_to_multi(self, join_type):\n # GH 20475\n leftindex = MultiIndex.from_product(\n [list("abc"), list("xy"), [1, 2]], names=["abc", "xy", "num"]\n )\n left = DataFrame({"v1": range(12)}, index=leftindex)\n\n rightindex = MultiIndex.from_product(\n [list("abc"), list("xy")], names=["abc", "xy"]\n )\n right = DataFrame({"v2": [100 * i for i in range(1, 7)]}, index=rightindex)\n\n result = left.join(right, on=["abc", "xy"], how=join_type)\n expected = (\n left.reset_index()\n .merge(right.reset_index(), on=["abc", "xy"], how=join_type)\n .set_index(["abc", "xy", "num"])\n )\n tm.assert_frame_equal(expected, result)\n\n msg = r'len\(left_on\) must equal the number of levels in the index of "right"'\n with pytest.raises(ValueError, match=msg):\n left.join(right, on="xy", how=join_type)\n\n with pytest.raises(ValueError, match=msg):\n right.join(left, on=["abc", "xy"], how=join_type)\n\n def test_join_on_tz_aware_datetimeindex(self):\n # GH 23931, 26335\n df1 = DataFrame(\n {\n "date": pd.date_range(\n start="2018-01-01", periods=5, tz="America/Chicago"\n ),\n "vals": list("abcde"),\n }\n )\n\n df2 = DataFrame(\n {\n "date": pd.date_range(\n start="2018-01-03", periods=5, tz="America/Chicago"\n ),\n "vals_2": list("tuvwx"),\n }\n )\n result = df1.join(df2.set_index("date"), on="date")\n expected = df1.copy()\n expected["vals_2"] = Series([np.nan] * 2 + list("tuv"))\n tm.assert_frame_equal(result, expected)\n\n def test_join_datetime_string(self):\n # GH 5647\n dfa = DataFrame(\n [\n ["2012-08-02", "L", 10],\n ["2012-08-02", "J", 15],\n ["2013-04-06", "L", 20],\n ["2013-04-06", "J", 25],\n ],\n columns=["x", "y", "a"],\n )\n dfa["x"] = pd.to_datetime(dfa["x"]).astype("M8[ns]")\n dfb = DataFrame(\n [["2012-08-02", "J", 1], ["2013-04-06", "L", 2]],\n columns=["x", "y", "z"],\n index=[2, 4],\n )\n dfb["x"] = pd.to_datetime(dfb["x"]).astype("M8[ns]")\n result = dfb.join(dfa.set_index(["x", "y"]), on=["x", "y"])\n expected = DataFrame(\n [\n [Timestamp("2012-08-02 00:00:00"), "J", 1, 15],\n [Timestamp("2013-04-06 00:00:00"), "L", 2, 20],\n ],\n index=[2, 4],\n columns=["x", "y", "z", "a"],\n )\n expected["x"] = expected["x"].astype("M8[ns]")\n tm.assert_frame_equal(result, expected)\n\n def test_join_with_categorical_index(self):\n # GH47812\n ix = ["a", "b"]\n id1 = pd.CategoricalIndex(ix, categories=ix)\n id2 = pd.CategoricalIndex(reversed(ix), categories=reversed(ix))\n\n df1 = DataFrame({"c1": ix}, index=id1)\n df2 = DataFrame({"c2": reversed(ix)}, index=id2)\n result = df1.join(df2)\n expected = DataFrame(\n {"c1": ["a", "b"], "c2": ["a", "b"]},\n index=pd.CategoricalIndex(["a", "b"], categories=["a", "b"]),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix="_y"):\n # some smoke tests\n for c in join_col:\n assert result[c].notna().all()\n\n left_grouped = left.groupby(join_col)\n right_grouped = right.groupby(join_col)\n\n for group_key, group in result.groupby(join_col):\n l_joined = _restrict_to_columns(group, left.columns, lsuffix)\n r_joined = _restrict_to_columns(group, right.columns, rsuffix)\n\n try:\n lgroup = left_grouped.get_group(group_key)\n except KeyError as err:\n if how in ("left", "inner"):\n raise AssertionError(\n f"key {group_key} should not have been in the join"\n ) from err\n\n _assert_all_na(l_joined, left.columns, join_col)\n else:\n _assert_same_contents(l_joined, lgroup)\n\n try:\n rgroup = right_grouped.get_group(group_key)\n except KeyError as err:\n if how in ("right", "inner"):\n raise AssertionError(\n f"key {group_key} should not have been in the join"\n ) from err\n\n _assert_all_na(r_joined, right.columns, join_col)\n else:\n _assert_same_contents(r_joined, rgroup)\n\n\ndef _restrict_to_columns(group, columns, suffix):\n found = [\n c for c in group.columns if c in columns or c.replace(suffix, "") in columns\n ]\n\n # filter\n group = group.loc[:, found]\n\n # get rid of suffixes, if any\n group = group.rename(columns=lambda x: x.replace(suffix, ""))\n\n # put in the right order...\n group = group.loc[:, columns]\n\n return group\n\n\ndef _assert_same_contents(join_chunk, source):\n NA_SENTINEL = -1234567 # drop_duplicates not so NA-friendly...\n\n jvalues = join_chunk.fillna(NA_SENTINEL).drop_duplicates().values\n svalues = source.fillna(NA_SENTINEL).drop_duplicates().values\n\n rows = {tuple(row) for row in jvalues}\n assert len(rows) == len(source)\n assert all(tuple(row) in rows for row in svalues)\n\n\ndef _assert_all_na(join_chunk, source_columns, join_col):\n for c in source_columns:\n if c in join_col:\n continue\n assert join_chunk[c].isna().all()\n\n\ndef _join_by_hand(a, b, how="left"):\n join_index = a.index.join(b.index, how=how)\n\n a_re = a.reindex(join_index)\n b_re = b.reindex(join_index)\n\n result_columns = a.columns.append(b.columns)\n\n for col, s in b_re.items():\n a_re[col] = s\n return a_re.reindex(columns=result_columns)\n\n\ndef test_join_inner_multiindex_deterministic_order():\n # GH: 36910\n left = DataFrame(\n data={"e": 5},\n index=MultiIndex.from_tuples([(1, 2, 4)], names=("a", "b", "d")),\n )\n right = DataFrame(\n data={"f": 6}, index=MultiIndex.from_tuples([(2, 3)], names=("b", "c"))\n )\n result = left.join(right, how="inner")\n expected = DataFrame(\n {"e": [5], "f": [6]},\n index=MultiIndex.from_tuples([(1, 2, 4, 3)], names=("a", "b", "d", "c")),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n ("input_col", "output_cols"), [("b", ["a", "b"]), ("a", ["a_x", "a_y"])]\n)\ndef test_join_cross(input_col, output_cols):\n # GH#5401\n left = DataFrame({"a": [1, 3]})\n right = DataFrame({input_col: [3, 4]})\n result = left.join(right, how="cross", lsuffix="_x", rsuffix="_y")\n expected = DataFrame({output_cols[0]: [1, 1, 3, 3], output_cols[1]: [3, 4, 3, 4]})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_join_multiindex_one_level(join_type):\n # GH#36909\n left = DataFrame(\n data={"c": 3}, index=MultiIndex.from_tuples([(1, 2)], names=("a", "b"))\n )\n right = DataFrame(data={"d": 4}, index=MultiIndex.from_tuples([(2,)], names=("b",)))\n result = left.join(right, how=join_type)\n if join_type == "right":\n expected = DataFrame(\n {"c": [3], "d": [4]},\n index=MultiIndex.from_tuples([(2, 1)], names=["b", "a"]),\n )\n else:\n expected = DataFrame(\n {"c": [3], "d": [4]},\n index=MultiIndex.from_tuples([(1, 2)], names=["a", "b"]),\n )\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "categories, values",\n [\n (["Y", "X"], ["Y", "X", "X"]),\n ([2, 1], [2, 1, 1]),\n ([2.5, 1.5], [2.5, 1.5, 1.5]),\n (\n [Timestamp("2020-12-31"), Timestamp("2019-12-31")],\n [Timestamp("2020-12-31"), Timestamp("2019-12-31"), Timestamp("2019-12-31")],\n ),\n ],\n)\ndef test_join_multiindex_not_alphabetical_categorical(categories, values):\n # GH#38502\n left = DataFrame(\n {\n "first": ["A", "A"],\n "second": Categorical(categories, categories=categories),\n "value": [1, 2],\n }\n ).set_index(["first", "second"])\n right = DataFrame(\n {\n "first": ["A", "A", "B"],\n "second": Categorical(values, categories=categories),\n "value": [3, 4, 5],\n }\n ).set_index(["first", "second"])\n result = left.join(right, lsuffix="_left", rsuffix="_right")\n\n expected = DataFrame(\n {\n "first": ["A", "A"],\n "second": Categorical(categories, categories=categories),\n "value_left": [1, 2],\n "value_right": [3, 4],\n }\n ).set_index(["first", "second"])\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "left_empty, how, exp",\n [\n (False, "left", "left"),\n (False, "right", "empty"),\n (False, "inner", "empty"),\n (False, "outer", "left"),\n (False, "cross", "empty"),\n (True, "left", "empty"),\n (True, "right", "right"),\n (True, "inner", "empty"),\n (True, "outer", "right"),\n (True, "cross", "empty"),\n ],\n)\ndef test_join_empty(left_empty, how, exp):\n left = DataFrame({"A": [2, 1], "B": [3, 4]}, dtype="int64").set_index("A")\n right = DataFrame({"A": [1], "C": [5]}, dtype="int64").set_index("A")\n\n if left_empty:\n left = left.head(0)\n else:\n right = right.head(0)\n\n result = left.join(right, how=how)\n\n if exp == "left":\n expected = DataFrame({"A": [2, 1], "B": [3, 4], "C": [np.nan, np.nan]})\n expected = expected.set_index("A")\n elif exp == "right":\n expected = DataFrame({"B": [np.nan], "A": [1], "C": [5]})\n expected = expected.set_index("A")\n elif exp == "empty":\n expected = DataFrame(columns=["B", "C"], dtype="int64")\n if how != "cross":\n expected = expected.rename_axis("A")\n if how == "outer":\n expected = expected.sort_index()\n\n tm.assert_frame_equal(result, expected)\n\n\ndef test_join_empty_uncomparable_columns():\n # GH 57048\n df1 = DataFrame()\n df2 = DataFrame(columns=["test"])\n df3 = DataFrame(columns=["foo", ("bar", "baz")])\n\n result = df1 + df2\n expected = DataFrame(columns=["test"])\n tm.assert_frame_equal(result, expected)\n\n result = df2 + df3\n expected = DataFrame(columns=[("bar", "baz"), "foo", "test"])\n tm.assert_frame_equal(result, expected)\n\n result = df1 + df3\n expected = DataFrame(columns=[("bar", "baz"), "foo"])\n tm.assert_frame_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "how, values",\n [\n ("inner", [0, 1, 2]),\n ("outer", [0, 1, 2]),\n ("left", [0, 1, 2]),\n ("right", [0, 2, 1]),\n ],\n)\ndef test_join_multiindex_categorical_output_index_dtype(how, values):\n # GH#50906\n df1 = DataFrame(\n {\n "a": Categorical([0, 1, 2]),\n "b": Categorical([0, 1, 2]),\n "c": [0, 1, 2],\n }\n ).set_index(["a", "b"])\n\n df2 = DataFrame(\n {\n "a": Categorical([0, 2, 1]),\n "b": Categorical([0, 2, 1]),\n "d": [0, 2, 1],\n }\n ).set_index(["a", "b"])\n\n expected = DataFrame(\n {\n "a": Categorical(values),\n "b": Categorical(values),\n "c": values,\n "d": values,\n }\n ).set_index(["a", "b"])\n\n result = df1.join(df2, how=how)\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\test_join.py
test_join.py
Python
37,848
0.95
0.074977
0.050321
awesome-app
315
2023-07-21T12:17:59.702103
MIT
true
e48d95b4859000edfe83214ef3de2789
import pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n)\nimport pandas._testing as tm\nfrom pandas.core.reshape.merge import (\n MergeError,\n merge,\n)\n\n\n@pytest.mark.parametrize(\n ("input_col", "output_cols"), [("b", ["a", "b"]), ("a", ["a_x", "a_y"])]\n)\ndef test_merge_cross(input_col, output_cols):\n # GH#5401\n left = DataFrame({"a": [1, 3]})\n right = DataFrame({input_col: [3, 4]})\n left_copy = left.copy()\n right_copy = right.copy()\n result = merge(left, right, how="cross")\n expected = DataFrame({output_cols[0]: [1, 1, 3, 3], output_cols[1]: [3, 4, 3, 4]})\n tm.assert_frame_equal(result, expected)\n tm.assert_frame_equal(left, left_copy)\n tm.assert_frame_equal(right, right_copy)\n\n\n@pytest.mark.parametrize(\n "kwargs",\n [\n {"left_index": True},\n {"right_index": True},\n {"on": "a"},\n {"left_on": "a"},\n {"right_on": "b"},\n ],\n)\ndef test_merge_cross_error_reporting(kwargs):\n # GH#5401\n left = DataFrame({"a": [1, 3]})\n right = DataFrame({"b": [3, 4]})\n msg = (\n "Can not pass on, right_on, left_on or set right_index=True or "\n "left_index=True"\n )\n with pytest.raises(MergeError, match=msg):\n merge(left, right, how="cross", **kwargs)\n\n\ndef test_merge_cross_mixed_dtypes():\n # GH#5401\n left = DataFrame(["a", "b", "c"], columns=["A"])\n right = DataFrame(range(2), columns=["B"])\n result = merge(left, right, how="cross")\n expected = DataFrame({"A": ["a", "a", "b", "b", "c", "c"], "B": [0, 1, 0, 1, 0, 1]})\n tm.assert_frame_equal(result, expected)\n\n\ndef test_merge_cross_more_than_one_column():\n # GH#5401\n left = DataFrame({"A": list("ab"), "B": [2, 1]})\n right = DataFrame({"C": range(2), "D": range(4, 6)})\n result = merge(left, right, how="cross")\n expected = DataFrame(\n {\n "A": ["a", "a", "b", "b"],\n "B": [2, 2, 1, 1],\n "C": [0, 1, 0, 1],\n "D": [4, 5, 4, 5],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_merge_cross_null_values(nulls_fixture):\n # GH#5401\n left = DataFrame({"a": [1, nulls_fixture]})\n right = DataFrame({"b": ["a", "b"], "c": [1.0, 2.0]})\n result = merge(left, right, how="cross")\n expected = DataFrame(\n {\n "a": [1, 1, nulls_fixture, nulls_fixture],\n "b": ["a", "b", "a", "b"],\n "c": [1.0, 2.0, 1.0, 2.0],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_join_cross_error_reporting():\n # GH#5401\n left = DataFrame({"a": [1, 3]})\n right = DataFrame({"a": [3, 4]})\n msg = (\n "Can not pass on, right_on, left_on or set right_index=True or "\n "left_index=True"\n )\n with pytest.raises(MergeError, match=msg):\n left.join(right, how="cross", on="a")\n\n\ndef test_merge_cross_series():\n # GH#54055\n ls = Series([1, 2, 3, 4], index=[1, 2, 3, 4], name="left")\n rs = Series([3, 4, 5, 6], index=[3, 4, 5, 6], name="right")\n res = merge(ls, rs, how="cross")\n\n expected = merge(ls.to_frame(), rs.to_frame(), how="cross")\n tm.assert_frame_equal(res, expected)\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\test_merge_cross.py
test_merge_cross.py
Python
3,146
0.95
0.063063
0.073684
vue-tools
349
2024-12-31T23:08:26.891994
Apache-2.0
true
4a606f2383a121fd4afa2afe3a7dc8f0
import numpy as np\nimport pytest\n\nfrom pandas import DataFrame\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef df1():\n return DataFrame(\n {\n "outer": [1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4],\n "inner": [1, 2, 3, 1, 2, 3, 4, 1, 2, 1, 2],\n "v1": np.linspace(0, 1, 11),\n }\n )\n\n\n@pytest.fixture\ndef df2():\n return DataFrame(\n {\n "outer": [1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3],\n "inner": [1, 2, 2, 3, 3, 4, 2, 3, 1, 1, 2, 3],\n "v2": np.linspace(10, 11, 12),\n }\n )\n\n\n@pytest.fixture(params=[[], ["outer"], ["outer", "inner"]])\ndef left_df(request, df1):\n """Construct left test DataFrame with specified levels\n (any of 'outer', 'inner', and 'v1')\n """\n levels = request.param\n if levels:\n df1 = df1.set_index(levels)\n\n return df1\n\n\n@pytest.fixture(params=[[], ["outer"], ["outer", "inner"]])\ndef right_df(request, df2):\n """Construct right test DataFrame with specified levels\n (any of 'outer', 'inner', and 'v2')\n """\n levels = request.param\n\n if levels:\n df2 = df2.set_index(levels)\n\n return df2\n\n\ndef compute_expected(df_left, df_right, on=None, left_on=None, right_on=None, how=None):\n """\n Compute the expected merge result for the test case.\n\n This method computes the expected result of merging two DataFrames on\n a combination of their columns and index levels. It does so by\n explicitly dropping/resetting their named index levels, performing a\n merge on their columns, and then finally restoring the appropriate\n index in the result.\n\n Parameters\n ----------\n df_left : DataFrame\n The left DataFrame (may have zero or more named index levels)\n df_right : DataFrame\n The right DataFrame (may have zero or more named index levels)\n on : list of str\n The on parameter to the merge operation\n left_on : list of str\n The left_on parameter to the merge operation\n right_on : list of str\n The right_on parameter to the merge operation\n how : str\n The how parameter to the merge operation\n\n Returns\n -------\n DataFrame\n The expected merge result\n """\n # Handle on param if specified\n if on is not None:\n left_on, right_on = on, on\n\n # Compute input named index levels\n left_levels = [n for n in df_left.index.names if n is not None]\n right_levels = [n for n in df_right.index.names if n is not None]\n\n # Compute output named index levels\n output_levels = [i for i in left_on if i in right_levels and i in left_levels]\n\n # Drop index levels that aren't involved in the merge\n drop_left = [n for n in left_levels if n not in left_on]\n if drop_left:\n df_left = df_left.reset_index(drop_left, drop=True)\n\n drop_right = [n for n in right_levels if n not in right_on]\n if drop_right:\n df_right = df_right.reset_index(drop_right, drop=True)\n\n # Convert remaining index levels to columns\n reset_left = [n for n in left_levels if n in left_on]\n if reset_left:\n df_left = df_left.reset_index(level=reset_left)\n\n reset_right = [n for n in right_levels if n in right_on]\n if reset_right:\n df_right = df_right.reset_index(level=reset_right)\n\n # Perform merge\n expected = df_left.merge(df_right, left_on=left_on, right_on=right_on, how=how)\n\n # Restore index levels\n if output_levels:\n expected = expected.set_index(output_levels)\n\n return expected\n\n\n@pytest.mark.parametrize(\n "on,how",\n [\n (["outer"], "inner"),\n (["inner"], "left"),\n (["outer", "inner"], "right"),\n (["inner", "outer"], "outer"),\n ],\n)\ndef test_merge_indexes_and_columns_on(left_df, right_df, on, how):\n # Construct expected result\n expected = compute_expected(left_df, right_df, on=on, how=how)\n\n # Perform merge\n result = left_df.merge(right_df, on=on, how=how)\n tm.assert_frame_equal(result, expected, check_like=True)\n\n\n@pytest.mark.parametrize(\n "left_on,right_on,how",\n [\n (["outer"], ["outer"], "inner"),\n (["inner"], ["inner"], "right"),\n (["outer", "inner"], ["outer", "inner"], "left"),\n (["inner", "outer"], ["inner", "outer"], "outer"),\n ],\n)\ndef test_merge_indexes_and_columns_lefton_righton(\n left_df, right_df, left_on, right_on, how\n):\n # Construct expected result\n expected = compute_expected(\n left_df, right_df, left_on=left_on, right_on=right_on, how=how\n )\n\n # Perform merge\n result = left_df.merge(right_df, left_on=left_on, right_on=right_on, how=how)\n tm.assert_frame_equal(result, expected, check_like=True)\n\n\n@pytest.mark.parametrize("left_index", ["inner", ["inner", "outer"]])\ndef test_join_indexes_and_columns_on(df1, df2, left_index, join_type):\n # Construct left_df\n left_df = df1.set_index(left_index)\n\n # Construct right_df\n right_df = df2.set_index(["outer", "inner"])\n\n # Result\n expected = (\n left_df.reset_index()\n .join(\n right_df, on=["outer", "inner"], how=join_type, lsuffix="_x", rsuffix="_y"\n )\n .set_index(left_index)\n )\n\n # Perform join\n result = left_df.join(\n right_df, on=["outer", "inner"], how=join_type, lsuffix="_x", rsuffix="_y"\n )\n\n tm.assert_frame_equal(result, expected, check_like=True)\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\test_merge_index_as_string.py
test_merge_index_as_string.py
Python
5,357
0.95
0.172043
0.101351
react-lib
507
2024-10-05T22:06:33.688891
Apache-2.0
true
801261a0aaf26be134602c63e04309e8
import re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n merge_ordered,\n)\nimport pandas._testing as tm\n\n\n@pytest.fixture\ndef left():\n return DataFrame({"key": ["a", "c", "e"], "lvalue": [1, 2.0, 3]})\n\n\n@pytest.fixture\ndef right():\n return DataFrame({"key": ["b", "c", "d", "f"], "rvalue": [1, 2, 3.0, 4]})\n\n\nclass TestMergeOrdered:\n def test_basic(self, left, right):\n result = merge_ordered(left, right, on="key")\n expected = DataFrame(\n {\n "key": ["a", "b", "c", "d", "e", "f"],\n "lvalue": [1, np.nan, 2, np.nan, 3, np.nan],\n "rvalue": [np.nan, 1, 2, 3, np.nan, 4],\n }\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_ffill(self, left, right):\n result = merge_ordered(left, right, on="key", fill_method="ffill")\n expected = DataFrame(\n {\n "key": ["a", "b", "c", "d", "e", "f"],\n "lvalue": [1.0, 1, 2, 2, 3, 3.0],\n "rvalue": [np.nan, 1, 2, 3, 3, 4],\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_multigroup(self, left, right):\n left = pd.concat([left, left], ignore_index=True)\n\n left["group"] = ["a"] * 3 + ["b"] * 3\n\n result = merge_ordered(\n left, right, on="key", left_by="group", fill_method="ffill"\n )\n expected = DataFrame(\n {\n "key": ["a", "b", "c", "d", "e", "f"] * 2,\n "lvalue": [1.0, 1, 2, 2, 3, 3.0] * 2,\n "rvalue": [np.nan, 1, 2, 3, 3, 4] * 2,\n }\n )\n expected["group"] = ["a"] * 6 + ["b"] * 6\n\n tm.assert_frame_equal(result, expected.loc[:, result.columns])\n\n result2 = merge_ordered(\n right, left, on="key", right_by="group", fill_method="ffill"\n )\n tm.assert_frame_equal(result, result2.loc[:, result.columns])\n\n result = merge_ordered(left, right, on="key", left_by="group")\n assert result["group"].notna().all()\n\n @pytest.mark.filterwarnings(\n "ignore:Passing a BlockManager|Passing a SingleBlockManager:DeprecationWarning"\n )\n def test_merge_type(self, left, right):\n class NotADataFrame(DataFrame):\n @property\n def _constructor(self):\n return NotADataFrame\n\n nad = NotADataFrame(left)\n result = nad.merge(right, on="key")\n\n assert isinstance(result, NotADataFrame)\n\n @pytest.mark.parametrize(\n "df_seq, pattern",\n [\n ((), "[Nn]o objects"),\n ([], "[Nn]o objects"),\n ({}, "[Nn]o objects"),\n ([None], "objects.*None"),\n ([None, None], "objects.*None"),\n ],\n )\n def test_empty_sequence_concat(self, df_seq, pattern):\n # GH 9157\n with pytest.raises(ValueError, match=pattern):\n pd.concat(df_seq)\n\n @pytest.mark.parametrize(\n "arg", [[DataFrame()], [None, DataFrame()], [DataFrame(), None]]\n )\n def test_empty_sequence_concat_ok(self, arg):\n pd.concat(arg)\n\n def test_doc_example(self):\n left = DataFrame(\n {\n "group": list("aaabbb"),\n "key": ["a", "c", "e", "a", "c", "e"],\n "lvalue": [1, 2, 3] * 2,\n }\n )\n\n right = DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]})\n\n result = merge_ordered(left, right, fill_method="ffill", left_by="group")\n\n expected = DataFrame(\n {\n "group": list("aaaaabbbbb"),\n "key": ["a", "b", "c", "d", "e"] * 2,\n "lvalue": [1, 1, 2, 2, 3] * 2,\n "rvalue": [np.nan, 1, 2, 3, 3] * 2,\n }\n )\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "left, right, on, left_by, right_by, expected",\n [\n (\n DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),\n DataFrame({"T": [2], "E": [1]}),\n ["T"],\n ["G", "H"],\n None,\n DataFrame(\n {\n "G": ["g"] * 3,\n "H": ["h"] * 3,\n "T": [1, 2, 3],\n "E": [np.nan, 1.0, np.nan],\n }\n ),\n ),\n (\n DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),\n DataFrame({"T": [2], "E": [1]}),\n "T",\n ["G", "H"],\n None,\n DataFrame(\n {\n "G": ["g"] * 3,\n "H": ["h"] * 3,\n "T": [1, 2, 3],\n "E": [np.nan, 1.0, np.nan],\n }\n ),\n ),\n (\n DataFrame({"T": [2], "E": [1]}),\n DataFrame({"G": ["g", "g"], "H": ["h", "h"], "T": [1, 3]}),\n ["T"],\n None,\n ["G", "H"],\n DataFrame(\n {\n "T": [1, 2, 3],\n "E": [np.nan, 1.0, np.nan],\n "G": ["g"] * 3,\n "H": ["h"] * 3,\n }\n ),\n ),\n ],\n )\n def test_list_type_by(self, left, right, on, left_by, right_by, expected):\n # GH 35269\n result = merge_ordered(\n left=left,\n right=right,\n on=on,\n left_by=left_by,\n right_by=right_by,\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_left_by_length_equals_to_right_shape0(self):\n # GH 38166\n left = DataFrame([["g", "h", 1], ["g", "h", 3]], columns=list("GHE"))\n right = DataFrame([[2, 1]], columns=list("ET"))\n result = merge_ordered(left, right, on="E", left_by=["G", "H"])\n expected = DataFrame(\n {"G": ["g"] * 3, "H": ["h"] * 3, "E": [1, 2, 3], "T": [np.nan, 1.0, np.nan]}\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_elements_not_in_by_but_in_df(self):\n # GH 38167\n left = DataFrame([["g", "h", 1], ["g", "h", 3]], columns=list("GHE"))\n right = DataFrame([[2, 1]], columns=list("ET"))\n msg = r"\{'h'\} not found in left columns"\n with pytest.raises(KeyError, match=msg):\n merge_ordered(left, right, on="E", left_by=["G", "h"])\n\n @pytest.mark.parametrize("invalid_method", ["linear", "carrot"])\n def test_ffill_validate_fill_method(self, left, right, invalid_method):\n # GH 55884\n with pytest.raises(\n ValueError, match=re.escape("fill_method must be 'ffill' or None")\n ):\n merge_ordered(left, right, on="key", fill_method=invalid_method)\n\n def test_ffill_left_merge(self):\n # GH 57010\n df1 = DataFrame(\n {\n "key": ["a", "c", "e", "a", "c", "e"],\n "lvalue": [1, 2, 3, 1, 2, 3],\n "group": ["a", "a", "a", "b", "b", "b"],\n }\n )\n df2 = DataFrame({"key": ["b", "c", "d"], "rvalue": [1, 2, 3]})\n result = merge_ordered(\n df1, df2, fill_method="ffill", left_by="group", how="left"\n )\n expected = DataFrame(\n {\n "key": ["a", "c", "e", "a", "c", "e"],\n "lvalue": [1, 2, 3, 1, 2, 3],\n "group": ["a", "a", "a", "b", "b", "b"],\n "rvalue": [np.nan, 2.0, 2.0, np.nan, 2.0, 2.0],\n }\n )\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\test_merge_ordered.py
test_merge_ordered.py
Python
7,731
0.95
0.069672
0.028436
awesome-app
254
2025-05-06T03:54:27.818173
GPL-3.0
true
5ce70c237c9b4c15b50a0f63cf66d015
import numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n MultiIndex,\n RangeIndex,\n Series,\n Timestamp,\n option_context,\n)\nimport pandas._testing as tm\nfrom pandas.core.reshape.concat import concat\nfrom pandas.core.reshape.merge import merge\n\n\n@pytest.fixture\ndef left():\n """left dataframe (not multi-indexed) for multi-index join tests"""\n # a little relevant example with NAs\n key1 = ["bar", "bar", "bar", "foo", "foo", "baz", "baz", "qux", "qux", "snap"]\n key2 = ["two", "one", "three", "one", "two", "one", "two", "two", "three", "one"]\n\n data = np.random.default_rng(2).standard_normal(len(key1))\n return DataFrame({"key1": key1, "key2": key2, "data": data})\n\n\n@pytest.fixture\ndef right(multiindex_dataframe_random_data):\n """right dataframe (multi-indexed) for multi-index join tests"""\n df = multiindex_dataframe_random_data\n df.index.names = ["key1", "key2"]\n\n df.columns = ["j_one", "j_two", "j_three"]\n return df\n\n\n@pytest.fixture\ndef left_multi():\n return DataFrame(\n {\n "Origin": ["A", "A", "B", "B", "C"],\n "Destination": ["A", "B", "A", "C", "A"],\n "Period": ["AM", "AM", "IP", "AM", "OP"],\n "TripPurp": ["hbw", "nhb", "hbo", "nhb", "hbw"],\n "Trips": [1987, 3647, 2470, 4296, 4444],\n },\n columns=["Origin", "Destination", "Period", "TripPurp", "Trips"],\n ).set_index(["Origin", "Destination", "Period", "TripPurp"])\n\n\n@pytest.fixture\ndef right_multi():\n return DataFrame(\n {\n "Origin": ["A", "A", "B", "B", "C", "C", "E"],\n "Destination": ["A", "B", "A", "B", "A", "B", "F"],\n "Period": ["AM", "AM", "IP", "AM", "OP", "IP", "AM"],\n "LinkType": ["a", "b", "c", "b", "a", "b", "a"],\n "Distance": [100, 80, 90, 80, 75, 35, 55],\n },\n columns=["Origin", "Destination", "Period", "LinkType", "Distance"],\n ).set_index(["Origin", "Destination", "Period", "LinkType"])\n\n\n@pytest.fixture\ndef on_cols_multi():\n return ["Origin", "Destination", "Period"]\n\n\nclass TestMergeMulti:\n def test_merge_on_multikey(self, left, right, join_type):\n on_cols = ["key1", "key2"]\n result = left.join(right, on=on_cols, how=join_type).reset_index(drop=True)\n\n expected = merge(left, right.reset_index(), on=on_cols, how=join_type)\n\n tm.assert_frame_equal(result, expected)\n\n result = left.join(right, on=on_cols, how=join_type, sort=True).reset_index(\n drop=True\n )\n\n expected = merge(\n left, right.reset_index(), on=on_cols, how=join_type, sort=True\n )\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))]\n )\n @pytest.mark.parametrize("sort", [True, False])\n def test_left_join_multi_index(self, sort, infer_string):\n with option_context("future.infer_string", infer_string):\n icols = ["1st", "2nd", "3rd"]\n\n def bind_cols(df):\n iord = lambda a: 0 if a != a else ord(a)\n f = lambda ts: ts.map(iord) - ord("a")\n return f(df["1st"]) + f(df["3rd"]) * 1e2 + df["2nd"].fillna(0) * 10\n\n def run_asserts(left, right, sort):\n res = left.join(right, on=icols, how="left", sort=sort)\n\n assert len(left) < len(res) + 1\n assert not res["4th"].isna().any()\n assert not res["5th"].isna().any()\n\n tm.assert_series_equal(res["4th"], -res["5th"], check_names=False)\n result = bind_cols(res.iloc[:, :-2])\n tm.assert_series_equal(res["4th"], result, check_names=False)\n assert result.name is None\n\n if sort:\n tm.assert_frame_equal(res, res.sort_values(icols, kind="mergesort"))\n\n out = merge(left, right.reset_index(), on=icols, sort=sort, how="left")\n\n res.index = RangeIndex(len(res))\n tm.assert_frame_equal(out, res)\n\n lc = list(map(chr, np.arange(ord("a"), ord("z") + 1)))\n left = DataFrame(\n np.random.default_rng(2).choice(lc, (50, 2)), columns=["1st", "3rd"]\n )\n # Explicit cast to float to avoid implicit cast when setting nan\n left.insert(\n 1,\n "2nd",\n np.random.default_rng(2).integers(0, 10, len(left)).astype("float"),\n )\n\n i = np.random.default_rng(2).permutation(len(left))\n right = left.iloc[i].copy()\n\n left["4th"] = bind_cols(left)\n right["5th"] = -bind_cols(right)\n right.set_index(icols, inplace=True)\n\n run_asserts(left, right, sort)\n\n # inject some nulls\n left.loc[1::4, "1st"] = np.nan\n left.loc[2::5, "2nd"] = np.nan\n left.loc[3::6, "3rd"] = np.nan\n left["4th"] = bind_cols(left)\n\n i = np.random.default_rng(2).permutation(len(left))\n right = left.iloc[i, :-1]\n right["5th"] = -bind_cols(right)\n right.set_index(icols, inplace=True)\n\n run_asserts(left, right, sort)\n\n @pytest.mark.parametrize("sort", [False, True])\n def test_merge_right_vs_left(self, left, right, sort):\n # compare left vs right merge with multikey\n on_cols = ["key1", "key2"]\n merged_left_right = left.merge(\n right, left_on=on_cols, right_index=True, how="left", sort=sort\n )\n\n merge_right_left = right.merge(\n left, right_on=on_cols, left_index=True, how="right", sort=sort\n )\n\n # Reorder columns\n merge_right_left = merge_right_left[merged_left_right.columns]\n\n tm.assert_frame_equal(merged_left_right, merge_right_left)\n\n def test_merge_multiple_cols_with_mixed_cols_index(self):\n # GH29522\n s = Series(\n range(6),\n MultiIndex.from_product([["A", "B"], [1, 2, 3]], names=["lev1", "lev2"]),\n name="Amount",\n )\n df = DataFrame({"lev1": list("AAABBB"), "lev2": [1, 2, 3, 1, 2, 3], "col": 0})\n result = merge(df, s.reset_index(), on=["lev1", "lev2"])\n expected = DataFrame(\n {\n "lev1": list("AAABBB"),\n "lev2": [1, 2, 3, 1, 2, 3],\n "col": [0] * 6,\n "Amount": range(6),\n }\n )\n tm.assert_frame_equal(result, expected)\n\n def test_compress_group_combinations(self):\n # ~ 40000000 possible unique groups\n key1 = [str(i) for i in range(10000)]\n key1 = np.tile(key1, 2)\n key2 = key1[::-1]\n\n df = DataFrame(\n {\n "key1": key1,\n "key2": key2,\n "value1": np.random.default_rng(2).standard_normal(20000),\n }\n )\n\n df2 = DataFrame(\n {\n "key1": key1[::2],\n "key2": key2[::2],\n "value2": np.random.default_rng(2).standard_normal(10000),\n }\n )\n\n # just to hit the label compression code path\n merge(df, df2, how="outer")\n\n def test_left_join_index_preserve_order(self):\n on_cols = ["k1", "k2"]\n left = DataFrame(\n {\n "k1": [0, 1, 2] * 8,\n "k2": ["foo", "bar"] * 12,\n "v": np.array(np.arange(24), dtype=np.int64),\n }\n )\n\n index = MultiIndex.from_tuples([(2, "bar"), (1, "foo")])\n right = DataFrame({"v2": [5, 7]}, index=index)\n\n result = left.join(right, on=on_cols)\n\n expected = left.copy()\n expected["v2"] = np.nan\n expected.loc[(expected.k1 == 2) & (expected.k2 == "bar"), "v2"] = 5\n expected.loc[(expected.k1 == 1) & (expected.k2 == "foo"), "v2"] = 7\n\n tm.assert_frame_equal(result, expected)\n\n result.sort_values(on_cols, kind="mergesort", inplace=True)\n expected = left.join(right, on=on_cols, sort=True)\n\n tm.assert_frame_equal(result, expected)\n\n # test join with multi dtypes blocks\n left = DataFrame(\n {\n "k1": [0, 1, 2] * 8,\n "k2": ["foo", "bar"] * 12,\n "k3": np.array([0, 1, 2] * 8, dtype=np.float32),\n "v": np.array(np.arange(24), dtype=np.int32),\n }\n )\n\n index = MultiIndex.from_tuples([(2, "bar"), (1, "foo")])\n right = DataFrame({"v2": [5, 7]}, index=index)\n\n result = left.join(right, on=on_cols)\n\n expected = left.copy()\n expected["v2"] = np.nan\n expected.loc[(expected.k1 == 2) & (expected.k2 == "bar"), "v2"] = 5\n expected.loc[(expected.k1 == 1) & (expected.k2 == "foo"), "v2"] = 7\n\n tm.assert_frame_equal(result, expected)\n\n result = result.sort_values(on_cols, kind="mergesort")\n expected = left.join(right, on=on_cols, sort=True)\n\n tm.assert_frame_equal(result, expected)\n\n def test_left_join_index_multi_match_multiindex(self):\n left = DataFrame(\n [\n ["X", "Y", "C", "a"],\n ["W", "Y", "C", "e"],\n ["V", "Q", "A", "h"],\n ["V", "R", "D", "i"],\n ["X", "Y", "D", "b"],\n ["X", "Y", "A", "c"],\n ["W", "Q", "B", "f"],\n ["W", "R", "C", "g"],\n ["V", "Y", "C", "j"],\n ["X", "Y", "B", "d"],\n ],\n columns=["cola", "colb", "colc", "tag"],\n index=[3, 2, 0, 1, 7, 6, 4, 5, 9, 8],\n )\n\n right = DataFrame(\n [\n ["W", "R", "C", 0],\n ["W", "Q", "B", 3],\n ["W", "Q", "B", 8],\n ["X", "Y", "A", 1],\n ["X", "Y", "A", 4],\n ["X", "Y", "B", 5],\n ["X", "Y", "C", 6],\n ["X", "Y", "C", 9],\n ["X", "Q", "C", -6],\n ["X", "R", "C", -9],\n ["V", "Y", "C", 7],\n ["V", "R", "D", 2],\n ["V", "R", "D", -1],\n ["V", "Q", "A", -3],\n ],\n columns=["col1", "col2", "col3", "val"],\n ).set_index(["col1", "col2", "col3"])\n\n result = left.join(right, on=["cola", "colb", "colc"], how="left")\n\n expected = DataFrame(\n [\n ["X", "Y", "C", "a", 6],\n ["X", "Y", "C", "a", 9],\n ["W", "Y", "C", "e", np.nan],\n ["V", "Q", "A", "h", -3],\n ["V", "R", "D", "i", 2],\n ["V", "R", "D", "i", -1],\n ["X", "Y", "D", "b", np.nan],\n ["X", "Y", "A", "c", 1],\n ["X", "Y", "A", "c", 4],\n ["W", "Q", "B", "f", 3],\n ["W", "Q", "B", "f", 8],\n ["W", "R", "C", "g", 0],\n ["V", "Y", "C", "j", 7],\n ["X", "Y", "B", "d", 5],\n ],\n columns=["cola", "colb", "colc", "tag", "val"],\n index=[3, 3, 2, 0, 1, 1, 7, 6, 6, 4, 4, 5, 9, 8],\n )\n\n tm.assert_frame_equal(result, expected)\n\n result = left.join(right, on=["cola", "colb", "colc"], how="left", sort=True)\n\n expected = expected.sort_values(["cola", "colb", "colc"], kind="mergesort")\n\n tm.assert_frame_equal(result, expected)\n\n def test_left_join_index_multi_match(self):\n left = DataFrame(\n [["c", 0], ["b", 1], ["a", 2], ["b", 3]],\n columns=["tag", "val"],\n index=[2, 0, 1, 3],\n )\n\n right = DataFrame(\n [\n ["a", "v"],\n ["c", "w"],\n ["c", "x"],\n ["d", "y"],\n ["a", "z"],\n ["c", "r"],\n ["e", "q"],\n ["c", "s"],\n ],\n columns=["tag", "char"],\n ).set_index("tag")\n\n result = left.join(right, on="tag", how="left")\n\n expected = DataFrame(\n [\n ["c", 0, "w"],\n ["c", 0, "x"],\n ["c", 0, "r"],\n ["c", 0, "s"],\n ["b", 1, np.nan],\n ["a", 2, "v"],\n ["a", 2, "z"],\n ["b", 3, np.nan],\n ],\n columns=["tag", "val", "char"],\n index=[2, 2, 2, 2, 0, 1, 1, 3],\n )\n\n tm.assert_frame_equal(result, expected)\n\n result = left.join(right, on="tag", how="left", sort=True)\n expected2 = expected.sort_values("tag", kind="mergesort")\n\n tm.assert_frame_equal(result, expected2)\n\n # GH7331 - maintain left frame order in left merge\n result = merge(left, right.reset_index(), how="left", on="tag")\n expected.index = RangeIndex(len(expected))\n tm.assert_frame_equal(result, expected)\n\n def test_left_merge_na_buglet(self):\n left = DataFrame(\n {\n "id": list("abcde"),\n "v1": np.random.default_rng(2).standard_normal(5),\n "v2": np.random.default_rng(2).standard_normal(5),\n "dummy": list("abcde"),\n "v3": np.random.default_rng(2).standard_normal(5),\n },\n columns=["id", "v1", "v2", "dummy", "v3"],\n )\n right = DataFrame(\n {\n "id": ["a", "b", np.nan, np.nan, np.nan],\n "sv3": [1.234, 5.678, np.nan, np.nan, np.nan],\n }\n )\n\n result = merge(left, right, on="id", how="left")\n\n rdf = right.drop(["id"], axis=1)\n expected = left.join(rdf)\n tm.assert_frame_equal(result, expected)\n\n def test_merge_na_keys(self):\n data = [\n [1950, "A", 1.5],\n [1950, "B", 1.5],\n [1955, "B", 1.5],\n [1960, "B", np.nan],\n [1970, "B", 4.0],\n [1950, "C", 4.0],\n [1960, "C", np.nan],\n [1965, "C", 3.0],\n [1970, "C", 4.0],\n ]\n\n frame = DataFrame(data, columns=["year", "panel", "data"])\n\n other_data = [\n [1960, "A", np.nan],\n [1970, "A", np.nan],\n [1955, "A", np.nan],\n [1965, "A", np.nan],\n [1965, "B", np.nan],\n [1955, "C", np.nan],\n ]\n other = DataFrame(other_data, columns=["year", "panel", "data"])\n\n result = frame.merge(other, how="outer")\n\n expected = frame.fillna(-999).merge(other.fillna(-999), how="outer")\n expected = expected.replace(-999, np.nan)\n\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("klass", [None, np.asarray, Series, Index])\n def test_merge_datetime_index(self, klass):\n # see gh-19038\n df = DataFrame(\n [1, 2, 3], ["2016-01-01", "2017-01-01", "2018-01-01"], columns=["a"]\n )\n df.index = pd.to_datetime(df.index)\n on_vector = df.index.year\n\n if klass is not None:\n on_vector = klass(on_vector)\n\n exp_years = np.array([2016, 2017, 2018], dtype=np.int32)\n expected = DataFrame({"a": [1, 2, 3], "key_1": exp_years})\n\n result = df.merge(df, on=["a", on_vector], how="inner")\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame({"key_0": exp_years, "a_x": [1, 2, 3], "a_y": [1, 2, 3]})\n\n result = df.merge(df, on=[df.index.year], how="inner")\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("merge_type", ["left", "right"])\n def test_merge_datetime_multi_index_empty_df(self, merge_type):\n # see gh-36895\n\n left = DataFrame(\n data={\n "data": [1.5, 1.5],\n },\n index=MultiIndex.from_tuples(\n [[Timestamp("1950-01-01"), "A"], [Timestamp("1950-01-02"), "B"]],\n names=["date", "panel"],\n ),\n )\n\n right = DataFrame(\n index=MultiIndex.from_tuples([], names=["date", "panel"]), columns=["state"]\n )\n\n expected_index = MultiIndex.from_tuples(\n [[Timestamp("1950-01-01"), "A"], [Timestamp("1950-01-02"), "B"]],\n names=["date", "panel"],\n )\n\n if merge_type == "left":\n expected = DataFrame(\n data={\n "data": [1.5, 1.5],\n "state": np.array([np.nan, np.nan], dtype=object),\n },\n index=expected_index,\n )\n results_merge = left.merge(right, how="left", on=["date", "panel"])\n results_join = left.join(right, how="left")\n else:\n expected = DataFrame(\n data={\n "state": np.array([np.nan, np.nan], dtype=object),\n "data": [1.5, 1.5],\n },\n index=expected_index,\n )\n results_merge = right.merge(left, how="right", on=["date", "panel"])\n results_join = right.join(left, how="right")\n\n tm.assert_frame_equal(results_merge, expected)\n tm.assert_frame_equal(results_join, expected)\n\n @pytest.fixture\n def household(self):\n household = DataFrame(\n {\n "household_id": [1, 2, 3],\n "male": [0, 1, 0],\n "wealth": [196087.3, 316478.7, 294750],\n },\n columns=["household_id", "male", "wealth"],\n ).set_index("household_id")\n return household\n\n @pytest.fixture\n def portfolio(self):\n portfolio = DataFrame(\n {\n "household_id": [1, 2, 2, 3, 3, 3, 4],\n "asset_id": [\n "nl0000301109",\n "nl0000289783",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "nl0000289965",\n np.nan,\n ],\n "name": [\n "ABN Amro",\n "Robeco",\n "Royal Dutch Shell",\n "Royal Dutch Shell",\n "AAB Eastern Europe Equity Fund",\n "Postbank BioTech Fonds",\n np.nan,\n ],\n "share": [1.0, 0.4, 0.6, 0.15, 0.6, 0.25, 1.0],\n },\n columns=["household_id", "asset_id", "name", "share"],\n ).set_index(["household_id", "asset_id"])\n return portfolio\n\n @pytest.fixture\n def expected(self):\n expected = (\n DataFrame(\n {\n "male": [0, 1, 1, 0, 0, 0],\n "wealth": [\n 196087.3,\n 316478.7,\n 316478.7,\n 294750.0,\n 294750.0,\n 294750.0,\n ],\n "name": [\n "ABN Amro",\n "Robeco",\n "Royal Dutch Shell",\n "Royal Dutch Shell",\n "AAB Eastern Europe Equity Fund",\n "Postbank BioTech Fonds",\n ],\n "share": [1.00, 0.40, 0.60, 0.15, 0.60, 0.25],\n "household_id": [1, 2, 2, 3, 3, 3],\n "asset_id": [\n "nl0000301109",\n "nl0000289783",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "nl0000289965",\n ],\n }\n )\n .set_index(["household_id", "asset_id"])\n .reindex(columns=["male", "wealth", "name", "share"])\n )\n return expected\n\n def test_join_multi_levels(self, portfolio, household, expected):\n portfolio = portfolio.copy()\n household = household.copy()\n\n # GH 3662\n # merge multi-levels\n result = household.join(portfolio, how="inner")\n tm.assert_frame_equal(result, expected)\n\n def test_join_multi_levels_merge_equivalence(self, portfolio, household, expected):\n portfolio = portfolio.copy()\n household = household.copy()\n\n # equivalency\n result = merge(\n household.reset_index(),\n portfolio.reset_index(),\n on=["household_id"],\n how="inner",\n ).set_index(["household_id", "asset_id"])\n tm.assert_frame_equal(result, expected)\n\n def test_join_multi_levels_outer(self, portfolio, household, expected):\n portfolio = portfolio.copy()\n household = household.copy()\n\n result = household.join(portfolio, how="outer")\n expected = concat(\n [\n expected,\n (\n DataFrame(\n {"share": [1.00]},\n index=MultiIndex.from_tuples(\n [(4, np.nan)], names=["household_id", "asset_id"]\n ),\n )\n ),\n ],\n axis=0,\n sort=True,\n ).reindex(columns=expected.columns)\n tm.assert_frame_equal(result, expected, check_index_type=False)\n\n def test_join_multi_levels_invalid(self, portfolio, household):\n portfolio = portfolio.copy()\n household = household.copy()\n\n # invalid cases\n household.index.name = "foo"\n\n with pytest.raises(\n ValueError, match="cannot join with no overlapping index names"\n ):\n household.join(portfolio, how="inner")\n\n portfolio2 = portfolio.copy()\n portfolio2.index.set_names(["household_id", "foo"])\n\n with pytest.raises(ValueError, match="columns overlap but no suffix specified"):\n portfolio2.join(portfolio, how="inner")\n\n def test_join_multi_levels2(self):\n # some more advanced merges\n # GH6360\n household = DataFrame(\n {\n "household_id": [1, 2, 2, 3, 3, 3, 4],\n "asset_id": [\n "nl0000301109",\n "nl0000301109",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "nl0000289965",\n np.nan,\n ],\n "share": [1.0, 0.4, 0.6, 0.15, 0.6, 0.25, 1.0],\n },\n columns=["household_id", "asset_id", "share"],\n ).set_index(["household_id", "asset_id"])\n\n log_return = DataFrame(\n {\n "asset_id": [\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "lu0197800237",\n ],\n "t": [233, 234, 235, 180, 181],\n "log_return": [\n 0.09604978,\n -0.06524096,\n 0.03532373,\n 0.03025441,\n 0.036997,\n ],\n }\n ).set_index(["asset_id", "t"])\n\n expected = (\n DataFrame(\n {\n "household_id": [2, 2, 2, 3, 3, 3, 3, 3],\n "asset_id": [\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "lu0197800237",\n ],\n "t": [233, 234, 235, 233, 234, 235, 180, 181],\n "share": [0.6, 0.6, 0.6, 0.15, 0.15, 0.15, 0.6, 0.6],\n "log_return": [\n 0.09604978,\n -0.06524096,\n 0.03532373,\n 0.09604978,\n -0.06524096,\n 0.03532373,\n 0.03025441,\n 0.036997,\n ],\n }\n )\n .set_index(["household_id", "asset_id", "t"])\n .reindex(columns=["share", "log_return"])\n )\n\n # this is the equivalency\n result = merge(\n household.reset_index(),\n log_return.reset_index(),\n on=["asset_id"],\n how="inner",\n ).set_index(["household_id", "asset_id", "t"])\n tm.assert_frame_equal(result, expected)\n\n expected = (\n DataFrame(\n {\n "household_id": [2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 2, 4],\n "asset_id": [\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "gb00b03mlx29",\n "lu0197800237",\n "lu0197800237",\n "nl0000289965",\n "nl0000301109",\n "nl0000301109",\n None,\n ],\n "t": [\n 233,\n 234,\n 235,\n 233,\n 234,\n 235,\n 180,\n 181,\n None,\n None,\n None,\n None,\n ],\n "share": [\n 0.6,\n 0.6,\n 0.6,\n 0.15,\n 0.15,\n 0.15,\n 0.6,\n 0.6,\n 0.25,\n 1.0,\n 0.4,\n 1.0,\n ],\n "log_return": [\n 0.09604978,\n -0.06524096,\n 0.03532373,\n 0.09604978,\n -0.06524096,\n 0.03532373,\n 0.03025441,\n 0.036997,\n None,\n None,\n None,\n None,\n ],\n }\n )\n .set_index(["household_id", "asset_id", "t"])\n .reindex(columns=["share", "log_return"])\n )\n\n result = merge(\n household.reset_index(),\n log_return.reset_index(),\n on=["asset_id"],\n how="outer",\n ).set_index(["household_id", "asset_id", "t"])\n\n tm.assert_frame_equal(result, expected)\n\n\nclass TestJoinMultiMulti:\n def test_join_multi_multi(self, left_multi, right_multi, join_type, on_cols_multi):\n left_names = left_multi.index.names\n right_names = right_multi.index.names\n if join_type == "right":\n level_order = right_names + left_names.difference(right_names)\n else:\n level_order = left_names + right_names.difference(left_names)\n # Multi-index join tests\n expected = (\n merge(\n left_multi.reset_index(),\n right_multi.reset_index(),\n how=join_type,\n on=on_cols_multi,\n )\n .set_index(level_order)\n .sort_index()\n )\n\n result = left_multi.join(right_multi, how=join_type).sort_index()\n tm.assert_frame_equal(result, expected)\n\n def test_join_multi_empty_frames(\n self, left_multi, right_multi, join_type, on_cols_multi\n ):\n left_multi = left_multi.drop(columns=left_multi.columns)\n right_multi = right_multi.drop(columns=right_multi.columns)\n\n left_names = left_multi.index.names\n right_names = right_multi.index.names\n if join_type == "right":\n level_order = right_names + left_names.difference(right_names)\n else:\n level_order = left_names + right_names.difference(left_names)\n\n expected = (\n merge(\n left_multi.reset_index(),\n right_multi.reset_index(),\n how=join_type,\n on=on_cols_multi,\n )\n .set_index(level_order)\n .sort_index()\n )\n\n result = left_multi.join(right_multi, how=join_type).sort_index()\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize("box", [None, np.asarray, Series, Index])\n def test_merge_datetime_index(self, box):\n # see gh-19038\n df = DataFrame(\n [1, 2, 3], ["2016-01-01", "2017-01-01", "2018-01-01"], columns=["a"]\n )\n df.index = pd.to_datetime(df.index)\n on_vector = df.index.year\n\n if box is not None:\n on_vector = box(on_vector)\n\n exp_years = np.array([2016, 2017, 2018], dtype=np.int32)\n expected = DataFrame({"a": [1, 2, 3], "key_1": exp_years})\n\n result = df.merge(df, on=["a", on_vector], how="inner")\n tm.assert_frame_equal(result, expected)\n\n expected = DataFrame({"key_0": exp_years, "a_x": [1, 2, 3], "a_y": [1, 2, 3]})\n\n result = df.merge(df, on=[df.index.year], how="inner")\n tm.assert_frame_equal(result, expected)\n\n def test_single_common_level(self):\n index_left = MultiIndex.from_tuples(\n [("K0", "X0"), ("K0", "X1"), ("K1", "X2")], names=["key", "X"]\n )\n\n left = DataFrame(\n {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}, index=index_left\n )\n\n index_right = MultiIndex.from_tuples(\n [("K0", "Y0"), ("K1", "Y1"), ("K2", "Y2"), ("K2", "Y3")], names=["key", "Y"]\n )\n\n right = DataFrame(\n {"C": ["C0", "C1", "C2", "C3"], "D": ["D0", "D1", "D2", "D3"]},\n index=index_right,\n )\n\n result = left.join(right)\n expected = merge(\n left.reset_index(), right.reset_index(), on=["key"], how="inner"\n ).set_index(["key", "X", "Y"])\n\n tm.assert_frame_equal(result, expected)\n\n def test_join_multi_wrong_order(self):\n # GH 25760\n # GH 28956\n\n midx1 = MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"])\n midx3 = MultiIndex.from_tuples([(4, 1), (3, 2), (3, 1)], names=["b", "a"])\n\n left = DataFrame(index=midx1, data={"x": [10, 20, 30, 40]})\n right = DataFrame(index=midx3, data={"y": ["foo", "bar", "fing"]})\n\n result = left.join(right)\n\n expected = DataFrame(\n index=midx1,\n data={"x": [10, 20, 30, 40], "y": ["fing", "foo", "bar", np.nan]},\n )\n\n tm.assert_frame_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\test_multi.py
test_multi.py
Python
31,130
0.95
0.047109
0.02904
python-kit
979
2025-06-11T11:16:58.728170
MIT
true
78b0ace81cb0c7a801ceedf29eb01b20
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_join.cpython-313.pyc
test_join.cpython-313.pyc
Other
54,338
0.95
0.005217
0.00885
react-lib
175
2024-02-12T10:00:20.851260
Apache-2.0
true
d1e75a5d182662f52a25442376be39e8
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_merge_asof.cpython-313.pyc
test_merge_asof.cpython-313.pyc
Other
83,028
0.6
0.002768
0.004028
react-lib
638
2023-09-29T18:53:08.702276
MIT
true
38089f0abb253a9c10cb62d1a530f846
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_merge_cross.cpython-313.pyc
test_merge_cross.cpython-313.pyc
Other
4,968
0.8
0
0
awesome-app
53
2024-01-02T09:28:01.848397
BSD-3-Clause
true
acb7d0c276bc710859fa13fb4ef47599
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_merge_index_as_string.cpython-313.pyc
test_merge_index_as_string.cpython-313.pyc
Other
6,475
0.8
0.010989
0
node-utils
580
2025-01-24T14:00:50.200378
Apache-2.0
true
7728c47116ceb76346c8265070981617
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_merge_ordered.cpython-313.pyc
test_merge_ordered.cpython-313.pyc
Other
10,571
0.8
0
0.023438
python-kit
853
2024-03-27T01:01:41.851809
BSD-3-Clause
true
14df9219627a4b9ea6da0f7d5af1edca
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\test_multi.cpython-313.pyc
test_multi.cpython-313.pyc
Other
35,208
0.8
0.005698
0.01462
vue-tools
523
2025-01-21T01:58:02.972265
Apache-2.0
true
9b71d083e271db55dea3b98a75803179
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\merge\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
react-lib
894
2025-06-12T03:49:11.346640
BSD-3-Clause
true
28d6c132a2c350212e60b6b1a7002e4d
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_crosstab.cpython-313.pyc
test_crosstab.cpython-313.pyc
Other
41,888
0.8
0
0.005837
python-kit
983
2024-01-09T04:27:06.800120
MIT
true
3644c486d52c8b0933e8032f324426f2
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_cut.cpython-313.pyc
test_cut.cpython-313.pyc
Other
39,296
0.8
0.005025
0.002577
node-utils
988
2023-09-04T22:47:26.888511
BSD-3-Clause
true
c41c6da7a3915bf45caebe2104b4869b
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_from_dummies.cpython-313.pyc
test_from_dummies.cpython-313.pyc
Other
16,937
0.8
0.005495
0
node-utils
151
2023-08-19T16:02:06.465312
GPL-3.0
true
1101676005c543186681bd8741118f08
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_get_dummies.cpython-313.pyc
test_get_dummies.cpython-313.pyc
Other
33,933
0.8
0.00545
0
vue-tools
717
2024-06-30T00:19:43.659724
GPL-3.0
true
aa7bd070b13f45c137bc0a7eb428c69b
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_melt.cpython-313.pyc
test_melt.cpython-313.pyc
Other
47,361
0.8
0
0.001845
react-lib
579
2023-08-23T21:00:02.264257
MIT
true
6d785834f90d13699266003f5753bfb2
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_pivot.cpython-313.pyc
test_pivot.cpython-313.pyc
Other
108,994
0.75
0.000767
0.007752
node-utils
674
2025-03-21T06:32:27.887558
Apache-2.0
true
f5eeb64546de7a6ba1e51571403768fa
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_pivot_multilevel.cpython-313.pyc
test_pivot_multilevel.cpython-313.pyc
Other
8,480
0.8
0
0
react-lib
921
2024-12-05T21:06:57.913258
GPL-3.0
true
e48ecf01aef3bff7f8f22b53bbf3100f
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_qcut.cpython-313.pyc
test_qcut.cpython-313.pyc
Other
14,686
0.8
0.005435
0.02907
vue-tools
732
2024-02-08T11:47:59.924927
GPL-3.0
true
2085bf1d7a62088dd9aff8e648519408
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_union_categoricals.cpython-313.pyc
test_union_categoricals.cpython-313.pyc
Other
19,860
0.8
0
0.00974
node-utils
369
2024-11-25T20:25:03.333936
BSD-3-Clause
true
f3857ec13433890309abd0b5fa15a80b
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\test_util.cpython-313.pyc
test_util.cpython-313.pyc
Other
5,743
0.8
0
0
awesome-app
994
2023-10-01T10:50:55.287043
GPL-3.0
true
16d52c3f258be239e9d8261d079669a3
\n\n
.venv\Lib\site-packages\pandas\tests\reshape\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
195
0.7
0
0
react-lib
866
2024-09-03T10:50:54.565975
MIT
true
ba73614af894bf9ff125b908ef181aa6
from datetime import (\n datetime,\n timedelta,\n)\nimport operator\n\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import iNaT\nfrom pandas.compat.numpy import np_version_gte1p24p3\n\nfrom pandas import (\n DatetimeIndex,\n DatetimeTZDtype,\n Index,\n NaT,\n Period,\n Series,\n Timedelta,\n TimedeltaIndex,\n Timestamp,\n isna,\n offsets,\n)\nimport pandas._testing as tm\nfrom pandas.core import roperator\nfrom pandas.core.arrays import (\n DatetimeArray,\n PeriodArray,\n TimedeltaArray,\n)\n\n\nclass TestNaTFormatting:\n def test_repr(self):\n assert repr(NaT) == "NaT"\n\n def test_str(self):\n assert str(NaT) == "NaT"\n\n def test_isoformat(self):\n assert NaT.isoformat() == "NaT"\n\n\n@pytest.mark.parametrize(\n "nat,idx",\n [\n (Timestamp("NaT"), DatetimeArray),\n (Timedelta("NaT"), TimedeltaArray),\n (Period("NaT", freq="M"), PeriodArray),\n ],\n)\ndef test_nat_fields(nat, idx):\n for field in idx._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == "weekday":\n continue\n\n result = getattr(NaT, field)\n assert np.isnan(result)\n\n result = getattr(nat, field)\n assert np.isnan(result)\n\n for field in idx._bool_ops:\n result = getattr(NaT, field)\n assert result is False\n\n result = getattr(nat, field)\n assert result is False\n\n\ndef test_nat_vector_field_access():\n idx = DatetimeIndex(["1/1/2000", None, None, "1/4/2000"])\n\n for field in DatetimeArray._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == "weekday":\n continue\n\n result = getattr(idx, field)\n expected = Index([getattr(x, field) for x in idx])\n tm.assert_index_equal(result, expected)\n\n ser = Series(idx)\n\n for field in DatetimeArray._field_ops:\n # weekday is a property of DTI, but a method\n # on NaT/Timestamp for compat with datetime\n if field == "weekday":\n continue\n\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n for field in DatetimeArray._bool_ops:\n result = getattr(ser.dt, field)\n expected = [getattr(x, field) for x in idx]\n tm.assert_series_equal(result, Series(expected))\n\n\n@pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period])\n@pytest.mark.parametrize(\n "value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat", "", "NAT"]\n)\ndef test_identity(klass, value):\n assert klass(value) is NaT\n\n\n@pytest.mark.parametrize("klass", [Timestamp, Timedelta])\n@pytest.mark.parametrize("method", ["round", "floor", "ceil"])\n@pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])\ndef test_round_nat(klass, method, freq):\n # see gh-14940\n ts = klass("nat")\n\n round_method = getattr(ts, method)\n assert round_method(freq) is ts\n\n\n@pytest.mark.parametrize(\n "method",\n [\n "astimezone",\n "combine",\n "ctime",\n "dst",\n "fromordinal",\n "fromtimestamp",\n "fromisocalendar",\n "isocalendar",\n "strftime",\n "strptime",\n "time",\n "timestamp",\n "timetuple",\n "timetz",\n "toordinal",\n "tzname",\n "utcfromtimestamp",\n "utcnow",\n "utcoffset",\n "utctimetuple",\n "timestamp",\n ],\n)\ndef test_nat_methods_raise(method):\n # see gh-9513, gh-17329\n msg = f"NaTType does not support {method}"\n\n with pytest.raises(ValueError, match=msg):\n getattr(NaT, method)()\n\n\n@pytest.mark.parametrize("method", ["weekday", "isoweekday"])\ndef test_nat_methods_nan(method):\n # see gh-9513, gh-17329\n assert np.isnan(getattr(NaT, method)())\n\n\n@pytest.mark.parametrize(\n "method", ["date", "now", "replace", "today", "tz_convert", "tz_localize"]\n)\ndef test_nat_methods_nat(method):\n # see gh-8254, gh-9513, gh-17329\n assert getattr(NaT, method)() is NaT\n\n\n@pytest.mark.parametrize(\n "get_nat", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)]\n)\ndef test_nat_iso_format(get_nat):\n # see gh-12300\n assert get_nat("NaT").isoformat() == "NaT"\n assert get_nat("NaT").isoformat(timespec="nanoseconds") == "NaT"\n\n\n@pytest.mark.parametrize(\n "klass,expected",\n [\n (Timestamp, ["normalize", "to_julian_date", "to_period", "unit"]),\n (\n Timedelta,\n [\n "components",\n "resolution_string",\n "to_pytimedelta",\n "to_timedelta64",\n "unit",\n "view",\n ],\n ),\n ],\n)\ndef test_missing_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # Here, we check which public methods NaT does not have. We\n # ignore any missing private methods.\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n missing = [x for x in klass_names if x not in nat_names and not x.startswith("_")]\n missing.sort()\n\n assert missing == expected\n\n\ndef _get_overlap_public_nat_methods(klass, as_tuple=False):\n """\n Get overlapping public methods between NaT and another class.\n\n Parameters\n ----------\n klass : type\n The class to compare with NaT\n as_tuple : bool, default False\n Whether to return a list of tuples of the form (klass, method).\n\n Returns\n -------\n overlap : list\n """\n nat_names = dir(NaT)\n klass_names = dir(klass)\n\n overlap = [\n x\n for x in nat_names\n if x in klass_names and not x.startswith("_") and callable(getattr(klass, x))\n ]\n\n # Timestamp takes precedence over Timedelta in terms of overlap.\n if klass is Timedelta:\n ts_names = dir(Timestamp)\n overlap = [x for x in overlap if x not in ts_names]\n\n if as_tuple:\n overlap = [(klass, method) for method in overlap]\n\n overlap.sort()\n return overlap\n\n\n@pytest.mark.parametrize(\n "klass,expected",\n [\n (\n Timestamp,\n [\n "as_unit",\n "astimezone",\n "ceil",\n "combine",\n "ctime",\n "date",\n "day_name",\n "dst",\n "floor",\n "fromisocalendar",\n "fromisoformat",\n "fromordinal",\n "fromtimestamp",\n "isocalendar",\n "isoformat",\n "isoweekday",\n "month_name",\n "now",\n "replace",\n "round",\n "strftime",\n "strptime",\n "time",\n "timestamp",\n "timetuple",\n "timetz",\n "to_datetime64",\n "to_numpy",\n "to_pydatetime",\n "today",\n "toordinal",\n "tz_convert",\n "tz_localize",\n "tzname",\n "utcfromtimestamp",\n "utcnow",\n "utcoffset",\n "utctimetuple",\n "weekday",\n ],\n ),\n (Timedelta, ["total_seconds"]),\n ],\n)\ndef test_overlap_public_nat_methods(klass, expected):\n # see gh-17327\n #\n # NaT should have *most* of the Timestamp and Timedelta methods.\n # In case when Timestamp, Timedelta, and NaT are overlap, the overlap\n # is considered to be with Timestamp and NaT, not Timedelta.\n assert _get_overlap_public_nat_methods(klass) == expected\n\n\n@pytest.mark.parametrize(\n "compare",\n (\n _get_overlap_public_nat_methods(Timestamp, True)\n + _get_overlap_public_nat_methods(Timedelta, True)\n ),\n ids=lambda x: f"{x[0].__name__}.{x[1]}",\n)\ndef test_nat_doc_strings(compare):\n # see gh-17327\n #\n # The docstrings for overlapping methods should match.\n klass, method = compare\n klass_doc = getattr(klass, method).__doc__\n\n if klass == Timestamp and method == "isoformat":\n pytest.skip(\n "Ignore differences with Timestamp.isoformat() as they're intentional"\n )\n\n if method == "to_numpy":\n # GH#44460 can return either dt64 or td64 depending on dtype,\n # different docstring is intentional\n pytest.skip(f"different docstring for {method} is intentional")\n\n nat_doc = getattr(NaT, method).__doc__\n assert klass_doc == nat_doc\n\n\n_ops = {\n "left_plus_right": lambda a, b: a + b,\n "right_plus_left": lambda a, b: b + a,\n "left_minus_right": lambda a, b: a - b,\n "right_minus_left": lambda a, b: b - a,\n "left_times_right": lambda a, b: a * b,\n "right_times_left": lambda a, b: b * a,\n "left_div_right": lambda a, b: a / b,\n "right_div_left": lambda a, b: b / a,\n}\n\n\n@pytest.mark.parametrize("op_name", list(_ops.keys()))\n@pytest.mark.parametrize(\n "value,val_type",\n [\n (2, "scalar"),\n (1.5, "floating"),\n (np.nan, "floating"),\n ("foo", "str"),\n (timedelta(3600), "timedelta"),\n (Timedelta("5s"), "timedelta"),\n (datetime(2014, 1, 1), "timestamp"),\n (Timestamp("2014-01-01"), "timestamp"),\n (Timestamp("2014-01-01", tz="UTC"), "timestamp"),\n (Timestamp("2014-01-01", tz="US/Eastern"), "timestamp"),\n (pytz.timezone("Asia/Tokyo").localize(datetime(2014, 1, 1)), "timestamp"),\n ],\n)\ndef test_nat_arithmetic_scalar(op_name, value, val_type):\n # see gh-6873\n invalid_ops = {\n "scalar": {"right_div_left"},\n "floating": {\n "right_div_left",\n "left_minus_right",\n "right_minus_left",\n "left_plus_right",\n "right_plus_left",\n },\n "str": set(_ops.keys()),\n "timedelta": {"left_times_right", "right_times_left"},\n "timestamp": {\n "left_times_right",\n "right_times_left",\n "left_div_right",\n "right_div_left",\n },\n }\n\n op = _ops[op_name]\n\n if op_name in invalid_ops.get(val_type, set()):\n if (\n val_type == "timedelta"\n and "times" in op_name\n and isinstance(value, Timedelta)\n ):\n typs = "(Timedelta|NaTType)"\n msg = rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'"\n elif val_type == "str":\n # un-specific check here because the message comes from str\n # and varies by method\n msg = "|".join(\n [\n "can only concatenate str",\n "unsupported operand type",\n "can't multiply sequence",\n "Can't convert 'NaTType'",\n "must be str, not NaTType",\n ]\n )\n else:\n msg = "unsupported operand type"\n\n with pytest.raises(TypeError, match=msg):\n op(NaT, value)\n else:\n if val_type == "timedelta" and "div" in op_name:\n expected = np.nan\n else:\n expected = NaT\n\n assert op(NaT, value) is expected\n\n\n@pytest.mark.parametrize(\n "val,expected", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64("NaT"), np.nan)]\n)\ndef test_nat_rfloordiv_timedelta(val, expected):\n # see gh-#18846\n #\n # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv\n td = Timedelta(hours=3, minutes=4)\n assert td // val is expected\n\n\n@pytest.mark.parametrize(\n "op_name",\n ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],\n)\n@pytest.mark.parametrize(\n "value",\n [\n DatetimeIndex(["2011-01-01", "2011-01-02"], name="x"),\n DatetimeIndex(["2011-01-01", "2011-01-02"], tz="US/Eastern", name="x"),\n DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"], dtype="M8[ns]"),\n DatetimeArray._from_sequence(\n ["2011-01-01", "2011-01-02"], dtype=DatetimeTZDtype(tz="US/Pacific")\n ),\n TimedeltaIndex(["1 day", "2 day"], name="x"),\n ],\n)\ndef test_nat_arithmetic_index(op_name, value):\n # see gh-11718\n exp_name = "x"\n exp_data = [NaT] * 2\n\n if value.dtype.kind == "M" and "plus" in op_name:\n expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name)\n else:\n expected = TimedeltaIndex(exp_data, name=exp_name)\n expected = expected.as_unit(value.unit)\n\n if not isinstance(value, Index):\n expected = expected.array\n\n op = _ops[op_name]\n result = op(NaT, value)\n tm.assert_equal(result, expected)\n\n\n@pytest.mark.parametrize(\n "op_name",\n ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],\n)\n@pytest.mark.parametrize("box", [TimedeltaIndex, Series, TimedeltaArray._from_sequence])\ndef test_nat_arithmetic_td64_vector(op_name, box):\n # see gh-19124\n vec = box(["1 day", "2 day"], dtype="timedelta64[ns]")\n box_nat = box([NaT, NaT], dtype="timedelta64[ns]")\n tm.assert_equal(_ops[op_name](vec, NaT), box_nat)\n\n\n@pytest.mark.parametrize(\n "dtype,op,out_dtype",\n [\n ("datetime64[ns]", operator.add, "datetime64[ns]"),\n ("datetime64[ns]", roperator.radd, "datetime64[ns]"),\n ("datetime64[ns]", operator.sub, "timedelta64[ns]"),\n ("datetime64[ns]", roperator.rsub, "timedelta64[ns]"),\n ("timedelta64[ns]", operator.add, "datetime64[ns]"),\n ("timedelta64[ns]", roperator.radd, "datetime64[ns]"),\n ("timedelta64[ns]", operator.sub, "datetime64[ns]"),\n ("timedelta64[ns]", roperator.rsub, "timedelta64[ns]"),\n ],\n)\ndef test_nat_arithmetic_ndarray(dtype, op, out_dtype):\n other = np.arange(10).astype(dtype)\n result = op(NaT, other)\n\n expected = np.empty(other.shape, dtype=out_dtype)\n expected.fill("NaT")\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_nat_pinned_docstrings():\n # see gh-17327\n assert NaT.ctime.__doc__ == Timestamp.ctime.__doc__\n\n\ndef test_to_numpy_alias():\n # GH 24653: alias .to_numpy() for scalars\n expected = NaT.to_datetime64()\n result = NaT.to_numpy()\n\n assert isna(expected) and isna(result)\n\n # GH#44460\n result = NaT.to_numpy("M8[s]")\n assert isinstance(result, np.datetime64)\n assert result.dtype == "M8[s]"\n\n result = NaT.to_numpy("m8[ns]")\n assert isinstance(result, np.timedelta64)\n assert result.dtype == "m8[ns]"\n\n result = NaT.to_numpy("m8[s]")\n assert isinstance(result, np.timedelta64)\n assert result.dtype == "m8[s]"\n\n with pytest.raises(ValueError, match="NaT.to_numpy dtype must be a "):\n NaT.to_numpy(np.int64)\n\n\n@pytest.mark.parametrize(\n "other",\n [\n Timedelta(0),\n Timedelta(0).to_pytimedelta(),\n pytest.param(\n Timedelta(0).to_timedelta64(),\n marks=pytest.mark.xfail(\n not np_version_gte1p24p3,\n reason="td64 doesn't return NotImplemented, see numpy#17017",\n # When this xfail is fixed, test_nat_comparisons_numpy\n # can be removed.\n ),\n ),\n Timestamp(0),\n Timestamp(0).to_pydatetime(),\n pytest.param(\n Timestamp(0).to_datetime64(),\n marks=pytest.mark.xfail(\n not np_version_gte1p24p3,\n reason="dt64 doesn't return NotImplemented, see numpy#17017",\n ),\n ),\n Timestamp(0).tz_localize("UTC"),\n NaT,\n ],\n)\ndef test_nat_comparisons(compare_operators_no_eq_ne, other):\n # GH 26039\n opname = compare_operators_no_eq_ne\n\n assert getattr(NaT, opname)(other) is False\n\n op = getattr(operator, opname.strip("_"))\n assert op(NaT, other) is False\n assert op(other, NaT) is False\n\n\n@pytest.mark.parametrize("other", [np.timedelta64(0, "ns"), np.datetime64("now", "ns")])\ndef test_nat_comparisons_numpy(other):\n # Once numpy#17017 is fixed and the xfailed cases in test_nat_comparisons\n # pass, this test can be removed\n assert not NaT == other\n assert NaT != other\n assert not NaT < other\n assert not NaT > other\n assert not NaT <= other\n assert not NaT >= other\n\n\n@pytest.mark.parametrize("other_and_type", [("foo", "str"), (2, "int"), (2.0, "float")])\n@pytest.mark.parametrize(\n "symbol_and_op",\n [("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt)],\n)\ndef test_nat_comparisons_invalid(other_and_type, symbol_and_op):\n # GH#35585\n other, other_type = other_and_type\n symbol, op = symbol_and_op\n\n assert not NaT == other\n assert not other == NaT\n\n assert NaT != other\n assert other != NaT\n\n msg = f"'{symbol}' not supported between instances of 'NaTType' and '{other_type}'"\n with pytest.raises(TypeError, match=msg):\n op(NaT, other)\n\n msg = f"'{symbol}' not supported between instances of '{other_type}' and 'NaTType'"\n with pytest.raises(TypeError, match=msg):\n op(other, NaT)\n\n\n@pytest.mark.parametrize(\n "other",\n [\n np.array(["foo"] * 2, dtype=object),\n np.array([2, 3], dtype="int64"),\n np.array([2.0, 3.5], dtype="float64"),\n ],\n ids=["str", "int", "float"],\n)\ndef test_nat_comparisons_invalid_ndarray(other):\n # GH#40722\n expected = np.array([False, False])\n result = NaT == other\n tm.assert_numpy_array_equal(result, expected)\n result = other == NaT\n tm.assert_numpy_array_equal(result, expected)\n\n expected = np.array([True, True])\n result = NaT != other\n tm.assert_numpy_array_equal(result, expected)\n result = other != NaT\n tm.assert_numpy_array_equal(result, expected)\n\n for symbol, op in [\n ("<=", operator.le),\n ("<", operator.lt),\n (">=", operator.ge),\n (">", operator.gt),\n ]:\n msg = f"'{symbol}' not supported between"\n\n with pytest.raises(TypeError, match=msg):\n op(NaT, other)\n\n if other.dtype == np.dtype("object"):\n # uses the reverse operator, so symbol changes\n msg = None\n with pytest.raises(TypeError, match=msg):\n op(other, NaT)\n\n\ndef test_compare_date(fixed_now_ts):\n # GH#39151 comparing NaT with date object is deprecated\n # See also: tests.scalar.timestamps.test_comparisons::test_compare_date\n\n dt = fixed_now_ts.to_pydatetime().date()\n\n msg = "Cannot compare NaT with datetime.date object"\n for left, right in [(NaT, dt), (dt, NaT)]:\n assert not left == right\n assert left != right\n\n with pytest.raises(TypeError, match=msg):\n left < right\n with pytest.raises(TypeError, match=msg):\n left <= right\n with pytest.raises(TypeError, match=msg):\n left > right\n with pytest.raises(TypeError, match=msg):\n left >= right\n\n\n@pytest.mark.parametrize(\n "obj",\n [\n offsets.YearEnd(2),\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.MonthEnd(2),\n offsets.MonthEnd(12),\n offsets.Day(2),\n offsets.Day(5),\n offsets.Hour(24),\n offsets.Hour(3),\n offsets.Minute(),\n np.timedelta64(3, "h"),\n np.timedelta64(4, "h"),\n np.timedelta64(3200, "s"),\n np.timedelta64(3600, "s"),\n np.timedelta64(3600 * 24, "s"),\n np.timedelta64(2, "D"),\n np.timedelta64(365, "D"),\n timedelta(-2),\n timedelta(365),\n timedelta(minutes=120),\n timedelta(days=4, minutes=180),\n timedelta(hours=23),\n timedelta(hours=23, minutes=30),\n timedelta(hours=48),\n ],\n)\ndef test_nat_addsub_tdlike_scalar(obj):\n assert NaT + obj is NaT\n assert obj + NaT is NaT\n assert NaT - obj is NaT\n\n\ndef test_pickle():\n # GH#4606\n p = tm.round_trip_pickle(NaT)\n assert p is NaT\n
.venv\Lib\site-packages\pandas\tests\scalar\test_nat.py
test_nat.py
Python
19,972
0.95
0.09732
0.081803
vue-tools
957
2023-09-22T13:11:37.932203
Apache-2.0
true
628d5398a6f5857595b13a226db8d5be
from datetime import (\n date,\n time,\n timedelta,\n)\nimport pickle\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.missing import NA\n\nfrom pandas.core.dtypes.common import is_scalar\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\ndef test_singleton():\n assert NA is NA\n new_NA = type(NA)()\n assert new_NA is NA\n\n\ndef test_repr():\n assert repr(NA) == "<NA>"\n assert str(NA) == "<NA>"\n\n\ndef test_format():\n # GH-34740\n assert format(NA) == "<NA>"\n assert format(NA, ">10") == " <NA>"\n assert format(NA, "xxx") == "<NA>" # NA is flexible, accept any format spec\n\n assert f"{NA}" == "<NA>"\n assert f"{NA:>10}" == " <NA>"\n assert f"{NA:xxx}" == "<NA>"\n\n\ndef test_truthiness():\n msg = "boolean value of NA is ambiguous"\n\n with pytest.raises(TypeError, match=msg):\n bool(NA)\n\n with pytest.raises(TypeError, match=msg):\n not NA\n\n\ndef test_hashable():\n assert hash(NA) == hash(NA)\n d = {NA: "test"}\n assert d[NA] == "test"\n\n\n@pytest.mark.parametrize(\n "other", [NA, 1, 1.0, "a", b"a", np.int64(1), np.nan], ids=repr\n)\ndef test_arithmetic_ops(all_arithmetic_functions, other):\n op = all_arithmetic_functions\n\n if op.__name__ in ("pow", "rpow", "rmod") and isinstance(other, (str, bytes)):\n pytest.skip(reason=f"{op.__name__} with NA and {other} not defined.")\n if op.__name__ in ("divmod", "rdivmod"):\n assert op(NA, other) is (NA, NA)\n else:\n if op.__name__ == "rpow":\n # avoid special case\n other += 1\n assert op(NA, other) is NA\n\n\n@pytest.mark.parametrize(\n "other",\n [\n NA,\n 1,\n 1.0,\n "a",\n b"a",\n np.int64(1),\n np.nan,\n np.bool_(True),\n time(0),\n date(1, 2, 3),\n timedelta(1),\n pd.NaT,\n ],\n)\ndef test_comparison_ops(comparison_op, other):\n assert comparison_op(NA, other) is NA\n assert comparison_op(other, NA) is NA\n\n\n@pytest.mark.parametrize(\n "value",\n [\n 0,\n 0.0,\n -0,\n -0.0,\n False,\n np.bool_(False),\n np.int_(0),\n np.float64(0),\n np.int_(-0),\n np.float64(-0),\n ],\n)\n@pytest.mark.parametrize("asarray", [True, False])\ndef test_pow_special(value, asarray):\n if asarray:\n value = np.array([value])\n result = NA**value\n\n if asarray:\n result = result[0]\n else:\n # this assertion isn't possible for ndarray.\n assert isinstance(result, type(value))\n assert result == 1\n\n\n@pytest.mark.parametrize(\n "value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float64(1)]\n)\n@pytest.mark.parametrize("asarray", [True, False])\ndef test_rpow_special(value, asarray):\n if asarray:\n value = np.array([value])\n result = value**NA\n\n if asarray:\n result = result[0]\n elif not isinstance(value, (np.float64, np.bool_, np.int_)):\n # this assertion isn't possible with asarray=True\n assert isinstance(result, type(value))\n\n assert result == value\n\n\n@pytest.mark.parametrize("value", [-1, -1.0, np.int_(-1), np.float64(-1)])\n@pytest.mark.parametrize("asarray", [True, False])\ndef test_rpow_minus_one(value, asarray):\n if asarray:\n value = np.array([value])\n result = value**NA\n\n if asarray:\n result = result[0]\n\n assert pd.isna(result)\n\n\ndef test_unary_ops():\n assert +NA is NA\n assert -NA is NA\n assert abs(NA) is NA\n assert ~NA is NA\n\n\ndef test_logical_and():\n assert NA & True is NA\n assert True & NA is NA\n assert NA & False is False\n assert False & NA is False\n assert NA & NA is NA\n\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n NA & 5\n\n\ndef test_logical_or():\n assert NA | True is True\n assert True | NA is True\n assert NA | False is NA\n assert False | NA is NA\n assert NA | NA is NA\n\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n NA | 5\n\n\ndef test_logical_xor():\n assert NA ^ True is NA\n assert True ^ NA is NA\n assert NA ^ False is NA\n assert False ^ NA is NA\n assert NA ^ NA is NA\n\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n NA ^ 5\n\n\ndef test_logical_not():\n assert ~NA is NA\n\n\n@pytest.mark.parametrize("shape", [(3,), (3, 3), (1, 2, 3)])\ndef test_arithmetic_ndarray(shape, all_arithmetic_functions):\n op = all_arithmetic_functions\n a = np.zeros(shape)\n if op.__name__ == "pow":\n a += 5\n result = op(NA, a)\n expected = np.full(a.shape, NA, dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n\ndef test_is_scalar():\n assert is_scalar(NA) is True\n\n\ndef test_isna():\n assert pd.isna(NA) is True\n assert pd.notna(NA) is False\n\n\ndef test_series_isna():\n s = pd.Series([1, NA], dtype=object)\n expected = pd.Series([False, True])\n tm.assert_series_equal(s.isna(), expected)\n\n\ndef test_ufunc():\n assert np.log(NA) is NA\n assert np.add(NA, 1) is NA\n result = np.divmod(NA, 1)\n assert result[0] is NA and result[1] is NA\n\n result = np.frexp(NA)\n assert result[0] is NA and result[1] is NA\n\n\ndef test_ufunc_raises():\n msg = "ufunc method 'at'"\n with pytest.raises(ValueError, match=msg):\n np.log.at(NA, 0)\n\n\ndef test_binary_input_not_dunder():\n a = np.array([1, 2, 3])\n expected = np.array([NA, NA, NA], dtype=object)\n result = np.logaddexp(a, NA)\n tm.assert_numpy_array_equal(result, expected)\n\n result = np.logaddexp(NA, a)\n tm.assert_numpy_array_equal(result, expected)\n\n # all NA, multiple inputs\n assert np.logaddexp(NA, NA) is NA\n\n result = np.modf(NA, NA)\n assert len(result) == 2\n assert all(x is NA for x in result)\n\n\ndef test_divmod_ufunc():\n # binary in, binary out.\n a = np.array([1, 2, 3])\n expected = np.array([NA, NA, NA], dtype=object)\n\n result = np.divmod(a, NA)\n assert isinstance(result, tuple)\n for arr in result:\n tm.assert_numpy_array_equal(arr, expected)\n tm.assert_numpy_array_equal(arr, expected)\n\n result = np.divmod(NA, a)\n for arr in result:\n tm.assert_numpy_array_equal(arr, expected)\n tm.assert_numpy_array_equal(arr, expected)\n\n\ndef test_integer_hash_collision_dict():\n # GH 30013\n result = {NA: "foo", hash(NA): "bar"}\n\n assert result[NA] == "foo"\n assert result[hash(NA)] == "bar"\n\n\ndef test_integer_hash_collision_set():\n # GH 30013\n result = {NA, hash(NA)}\n\n assert len(result) == 2\n assert NA in result\n assert hash(NA) in result\n\n\ndef test_pickle_roundtrip():\n # https://github.com/pandas-dev/pandas/issues/31847\n result = pickle.loads(pickle.dumps(NA))\n assert result is NA\n\n\ndef test_pickle_roundtrip_pandas():\n result = tm.round_trip_pickle(NA)\n assert result is NA\n\n\n@pytest.mark.parametrize(\n "values, dtype", [([1, 2, NA], "Int64"), (["A", "B", NA], "string")]\n)\n@pytest.mark.parametrize("as_frame", [True, False])\ndef test_pickle_roundtrip_containers(as_frame, values, dtype):\n s = pd.Series(pd.array(values, dtype=dtype))\n if as_frame:\n s = s.to_frame(name="A")\n result = tm.round_trip_pickle(s)\n tm.assert_equal(result, s)\n
.venv\Lib\site-packages\pandas\tests\scalar\test_na_scalar.py
test_na_scalar.py
Python
7,227
0.95
0.136076
0.038136
python-kit
956
2025-04-23T08:50:11.767058
Apache-2.0
true
41fd2328bcc23c99ab808dc582831a0c
from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n Interval,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\n\n\nclass TestIntervalArithmetic:\n def test_interval_add(self, closed):\n interval = Interval(0, 1, closed=closed)\n expected = Interval(1, 2, closed=closed)\n\n result = interval + 1\n assert result == expected\n\n result = 1 + interval\n assert result == expected\n\n result = interval\n result += 1\n assert result == expected\n\n msg = r"unsupported operand type\(s\) for \+"\n with pytest.raises(TypeError, match=msg):\n interval + interval\n\n with pytest.raises(TypeError, match=msg):\n interval + "foo"\n\n def test_interval_sub(self, closed):\n interval = Interval(0, 1, closed=closed)\n expected = Interval(-1, 0, closed=closed)\n\n result = interval - 1\n assert result == expected\n\n result = interval\n result -= 1\n assert result == expected\n\n msg = r"unsupported operand type\(s\) for -"\n with pytest.raises(TypeError, match=msg):\n interval - interval\n\n with pytest.raises(TypeError, match=msg):\n interval - "foo"\n\n def test_interval_mult(self, closed):\n interval = Interval(0, 1, closed=closed)\n expected = Interval(0, 2, closed=closed)\n\n result = interval * 2\n assert result == expected\n\n result = 2 * interval\n assert result == expected\n\n result = interval\n result *= 2\n assert result == expected\n\n msg = r"unsupported operand type\(s\) for \*"\n with pytest.raises(TypeError, match=msg):\n interval * interval\n\n msg = r"can\'t multiply sequence by non-int"\n with pytest.raises(TypeError, match=msg):\n interval * "foo"\n\n def test_interval_div(self, closed):\n interval = Interval(0, 1, closed=closed)\n expected = Interval(0, 0.5, closed=closed)\n\n result = interval / 2.0\n assert result == expected\n\n result = interval\n result /= 2.0\n assert result == expected\n\n msg = r"unsupported operand type\(s\) for /"\n with pytest.raises(TypeError, match=msg):\n interval / interval\n\n with pytest.raises(TypeError, match=msg):\n interval / "foo"\n\n def test_interval_floordiv(self, closed):\n interval = Interval(1, 2, closed=closed)\n expected = Interval(0, 1, closed=closed)\n\n result = interval // 2\n assert result == expected\n\n result = interval\n result //= 2\n assert result == expected\n\n msg = r"unsupported operand type\(s\) for //"\n with pytest.raises(TypeError, match=msg):\n interval // interval\n\n with pytest.raises(TypeError, match=msg):\n interval // "foo"\n\n @pytest.mark.parametrize("method", ["__add__", "__sub__"])\n @pytest.mark.parametrize(\n "interval",\n [\n Interval(\n Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00")\n ),\n Interval(Timedelta(days=7), Timedelta(days=14)),\n ],\n )\n @pytest.mark.parametrize(\n "delta", [Timedelta(days=7), timedelta(7), np.timedelta64(7, "D")]\n )\n def test_time_interval_add_subtract_timedelta(self, interval, delta, method):\n # https://github.com/pandas-dev/pandas/issues/32023\n result = getattr(interval, method)(delta)\n left = getattr(interval.left, method)(delta)\n right = getattr(interval.right, method)(delta)\n expected = Interval(left, right)\n\n assert result == expected\n\n @pytest.mark.parametrize("interval", [Interval(1, 2), Interval(1.0, 2.0)])\n @pytest.mark.parametrize(\n "delta", [Timedelta(days=7), timedelta(7), np.timedelta64(7, "D")]\n )\n def test_numeric_interval_add_timedelta_raises(self, interval, delta):\n # https://github.com/pandas-dev/pandas/issues/32023\n msg = "|".join(\n [\n "unsupported operand",\n "cannot use operands",\n "Only numeric, Timestamp and Timedelta endpoints are allowed",\n ]\n )\n with pytest.raises((TypeError, ValueError), match=msg):\n interval + delta\n\n with pytest.raises((TypeError, ValueError), match=msg):\n delta + interval\n\n @pytest.mark.parametrize("klass", [timedelta, np.timedelta64, Timedelta])\n def test_timedelta_add_timestamp_interval(self, klass):\n delta = klass(0)\n expected = Interval(Timestamp("2020-01-01"), Timestamp("2020-02-01"))\n\n result = delta + expected\n assert result == expected\n\n result = expected + delta\n assert result == expected\n\n\nclass TestIntervalComparisons:\n def test_interval_equal(self):\n assert Interval(0, 1) == Interval(0, 1, closed="right")\n assert Interval(0, 1) != Interval(0, 1, closed="left")\n assert Interval(0, 1) != 0\n\n def test_interval_comparison(self):\n msg = (\n "'<' not supported between instances of "\n "'pandas._libs.interval.Interval' and 'int'"\n )\n with pytest.raises(TypeError, match=msg):\n Interval(0, 1) < 2\n\n assert Interval(0, 1) < Interval(1, 2)\n assert Interval(0, 1) < Interval(0, 2)\n assert Interval(0, 1) < Interval(0.5, 1.5)\n assert Interval(0, 1) <= Interval(0, 1)\n assert Interval(0, 1) > Interval(-1, 2)\n assert Interval(0, 1) >= Interval(0, 1)\n\n def test_equality_comparison_broadcasts_over_array(self):\n # https://github.com/pandas-dev/pandas/issues/35931\n interval = Interval(0, 1)\n arr = np.array([interval, interval])\n result = interval == arr\n expected = np.array([True, True])\n tm.assert_numpy_array_equal(result, expected)\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_arithmetic.py
test_arithmetic.py
Python
5,937
0.95
0.09375
0.02
awesome-app
217
2024-03-10T14:13:32.937294
BSD-3-Clause
true
a49d8f37b408f5961dea6dcde2ceaffc
import pytest\n\nfrom pandas import (\n Interval,\n Period,\n Timestamp,\n)\n\n\nclass TestIntervalConstructors:\n @pytest.mark.parametrize(\n "left, right",\n [\n ("a", "z"),\n (("a", "b"), ("c", "d")),\n (list("AB"), list("ab")),\n (Interval(0, 1), Interval(1, 2)),\n (Period("2018Q1", freq="Q"), Period("2018Q1", freq="Q")),\n ],\n )\n def test_construct_errors(self, left, right):\n # GH#23013\n msg = "Only numeric, Timestamp and Timedelta endpoints are allowed"\n with pytest.raises(ValueError, match=msg):\n Interval(left, right)\n\n def test_constructor_errors(self):\n msg = "invalid option for 'closed': foo"\n with pytest.raises(ValueError, match=msg):\n Interval(0, 1, closed="foo")\n\n msg = "left side of interval must be <= right side"\n with pytest.raises(ValueError, match=msg):\n Interval(1, 0)\n\n @pytest.mark.parametrize(\n "tz_left, tz_right", [(None, "UTC"), ("UTC", None), ("UTC", "US/Eastern")]\n )\n def test_constructor_errors_tz(self, tz_left, tz_right):\n # GH#18538\n left = Timestamp("2017-01-01", tz=tz_left)\n right = Timestamp("2017-01-02", tz=tz_right)\n\n if tz_left is None or tz_right is None:\n error = TypeError\n msg = "Cannot compare tz-naive and tz-aware timestamps"\n else:\n error = ValueError\n msg = "left and right must have the same time zone"\n with pytest.raises(error, match=msg):\n Interval(left, right)\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_constructors.py
test_constructors.py
Python
1,599
0.95
0.117647
0.045455
awesome-app
404
2024-08-14T03:59:46.517226
GPL-3.0
true
5631bbbb9a363d5987d4b1611f10dc65
import pytest\n\nfrom pandas import (\n Interval,\n Timedelta,\n Timestamp,\n)\n\n\nclass TestContains:\n def test_contains(self):\n interval = Interval(0, 1)\n assert 0.5 in interval\n assert 1 in interval\n assert 0 not in interval\n\n interval_both = Interval(0, 1, "both")\n assert 0 in interval_both\n assert 1 in interval_both\n\n interval_neither = Interval(0, 1, closed="neither")\n assert 0 not in interval_neither\n assert 0.5 in interval_neither\n assert 1 not in interval_neither\n\n def test_contains_interval(self, inclusive_endpoints_fixture):\n interval1 = Interval(0, 1, "both")\n interval2 = Interval(0, 1, inclusive_endpoints_fixture)\n assert interval1 in interval1\n assert interval2 in interval2\n assert interval2 in interval1\n assert interval1 not in interval2 or inclusive_endpoints_fixture == "both"\n\n def test_contains_infinite_length(self):\n interval1 = Interval(0, 1, "both")\n interval2 = Interval(float("-inf"), float("inf"), "neither")\n assert interval1 in interval2\n assert interval2 not in interval1\n\n def test_contains_zero_length(self):\n interval1 = Interval(0, 1, "both")\n interval2 = Interval(-1, -1, "both")\n interval3 = Interval(0.5, 0.5, "both")\n assert interval2 not in interval1\n assert interval3 in interval1\n assert interval2 not in interval3 and interval3 not in interval2\n assert interval1 not in interval2 and interval1 not in interval3\n\n @pytest.mark.parametrize(\n "type1",\n [\n (0, 1),\n (Timestamp(2000, 1, 1, 0), Timestamp(2000, 1, 1, 1)),\n (Timedelta("0h"), Timedelta("1h")),\n ],\n )\n @pytest.mark.parametrize(\n "type2",\n [\n (0, 1),\n (Timestamp(2000, 1, 1, 0), Timestamp(2000, 1, 1, 1)),\n (Timedelta("0h"), Timedelta("1h")),\n ],\n )\n def test_contains_mixed_types(self, type1, type2):\n interval1 = Interval(*type1)\n interval2 = Interval(*type2)\n if type1 == type2:\n assert interval1 in interval2\n else:\n msg = "^'<=' not supported between instances of"\n with pytest.raises(TypeError, match=msg):\n interval1 in interval2\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_contains.py
test_contains.py
Python
2,354
0.85
0.09589
0
react-lib
605
2023-09-10T13:21:51.974137
GPL-3.0
true
c0c595cb8f3727c4fc58f389b380af71
from pandas import Interval\n\n\ndef test_interval_repr():\n interval = Interval(0, 1)\n assert repr(interval) == "Interval(0, 1, closed='right')"\n assert str(interval) == "(0, 1]"\n\n interval_left = Interval(0, 1, closed="left")\n assert repr(interval_left) == "Interval(0, 1, closed='left')"\n assert str(interval_left) == "[0, 1)"\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_formats.py
test_formats.py
Python
344
0.85
0.090909
0
node-utils
121
2024-08-10T03:22:18.958532
Apache-2.0
true
8b56eaee777cb2d2550935fb6e07e7ec
import numpy as np\nimport pytest\n\nfrom pandas import (\n Interval,\n Timedelta,\n Timestamp,\n)\n\n\n@pytest.fixture\ndef interval():\n return Interval(0, 1)\n\n\nclass TestInterval:\n def test_properties(self, interval):\n assert interval.closed == "right"\n assert interval.left == 0\n assert interval.right == 1\n assert interval.mid == 0.5\n\n def test_hash(self, interval):\n # should not raise\n hash(interval)\n\n @pytest.mark.parametrize(\n "left, right, expected",\n [\n (0, 5, 5),\n (-2, 5.5, 7.5),\n (10, 10, 0),\n (10, np.inf, np.inf),\n (-np.inf, -5, np.inf),\n (-np.inf, np.inf, np.inf),\n (Timedelta("0 days"), Timedelta("5 days"), Timedelta("5 days")),\n (Timedelta("10 days"), Timedelta("10 days"), Timedelta("0 days")),\n (Timedelta("1h10min"), Timedelta("5h5min"), Timedelta("3h55min")),\n (Timedelta("5s"), Timedelta("1h"), Timedelta("59min55s")),\n ],\n )\n def test_length(self, left, right, expected):\n # GH 18789\n iv = Interval(left, right)\n result = iv.length\n assert result == expected\n\n @pytest.mark.parametrize(\n "left, right, expected",\n [\n ("2017-01-01", "2017-01-06", "5 days"),\n ("2017-01-01", "2017-01-01 12:00:00", "12 hours"),\n ("2017-01-01 12:00", "2017-01-01 12:00:00", "0 days"),\n ("2017-01-01 12:01", "2017-01-05 17:31:00", "4 days 5 hours 30 min"),\n ],\n )\n @pytest.mark.parametrize("tz", (None, "UTC", "CET", "US/Eastern"))\n def test_length_timestamp(self, tz, left, right, expected):\n # GH 18789\n iv = Interval(Timestamp(left, tz=tz), Timestamp(right, tz=tz))\n result = iv.length\n expected = Timedelta(expected)\n assert result == expected\n\n @pytest.mark.parametrize(\n "left, right",\n [\n (0, 1),\n (Timedelta("0 days"), Timedelta("1 day")),\n (Timestamp("2018-01-01"), Timestamp("2018-01-02")),\n (\n Timestamp("2018-01-01", tz="US/Eastern"),\n Timestamp("2018-01-02", tz="US/Eastern"),\n ),\n ],\n )\n def test_is_empty(self, left, right, closed):\n # GH27219\n # non-empty always return False\n iv = Interval(left, right, closed)\n assert iv.is_empty is False\n\n # same endpoint is empty except when closed='both' (contains one point)\n iv = Interval(left, left, closed)\n result = iv.is_empty\n expected = closed != "both"\n assert result is expected\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_interval.py
test_interval.py
Python
2,656
0.95
0.08046
0.077922
node-utils
722
2023-09-19T14:34:48.639553
Apache-2.0
true
7b5e7b598240f3d7c87646aaf981caae
import pytest\n\nfrom pandas import (\n Interval,\n Timedelta,\n Timestamp,\n)\n\n\n@pytest.fixture(\n params=[\n (Timedelta("0 days"), Timedelta("1 day")),\n (Timestamp("2018-01-01"), Timedelta("1 day")),\n (0, 1),\n ],\n ids=lambda x: type(x[0]).__name__,\n)\ndef start_shift(request):\n """\n Fixture for generating intervals of types from a start value and a shift\n value that can be added to start to generate an endpoint\n """\n return request.param\n\n\nclass TestOverlaps:\n def test_overlaps_self(self, start_shift, closed):\n start, shift = start_shift\n interval = Interval(start, start + shift, closed)\n assert interval.overlaps(interval)\n\n def test_overlaps_nested(self, start_shift, closed, other_closed):\n start, shift = start_shift\n interval1 = Interval(start, start + 3 * shift, other_closed)\n interval2 = Interval(start + shift, start + 2 * shift, closed)\n\n # nested intervals should always overlap\n assert interval1.overlaps(interval2)\n\n def test_overlaps_disjoint(self, start_shift, closed, other_closed):\n start, shift = start_shift\n interval1 = Interval(start, start + shift, other_closed)\n interval2 = Interval(start + 2 * shift, start + 3 * shift, closed)\n\n # disjoint intervals should never overlap\n assert not interval1.overlaps(interval2)\n\n def test_overlaps_endpoint(self, start_shift, closed, other_closed):\n start, shift = start_shift\n interval1 = Interval(start, start + shift, other_closed)\n interval2 = Interval(start + shift, start + 2 * shift, closed)\n\n # overlap if shared endpoint is closed for both (overlap at a point)\n result = interval1.overlaps(interval2)\n expected = interval1.closed_right and interval2.closed_left\n assert result == expected\n\n @pytest.mark.parametrize(\n "other",\n [10, True, "foo", Timedelta("1 day"), Timestamp("2018-01-01")],\n ids=lambda x: type(x).__name__,\n )\n def test_overlaps_invalid_type(self, other):\n interval = Interval(0, 1)\n msg = f"`other` must be an Interval, got {type(other).__name__}"\n with pytest.raises(TypeError, match=msg):\n interval.overlaps(other)\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\test_overlaps.py
test_overlaps.py
Python
2,274
0.95
0.149254
0.054545
vue-tools
132
2024-02-10T02:25:25.917293
Apache-2.0
true
e5c628304f523abb57252a5221fd1774
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
9,467
0.8
0.05814
0
python-kit
130
2025-03-18T16:02:25.033656
MIT
true
f113526f1f39d3d725d1c1160226ac00
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
2,883
0.8
0.021739
0
python-kit
462
2024-11-25T05:57:59.921005
MIT
true
fe9f2cbb4b8c159b58b8522a04af3d96
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_contains.cpython-313.pyc
test_contains.cpython-313.pyc
Other
3,453
0.8
0
0
awesome-app
148
2025-03-31T05:05:04.137978
Apache-2.0
true
00d39e402125ec6187921a3bf043152c
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
784
0.7
0
0
react-lib
522
2024-07-06T06:21:36.952554
BSD-3-Clause
true
440bfe8a4bb04e938239e9a5d03c2fb3
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_interval.cpython-313.pyc
test_interval.cpython-313.pyc
Other
3,900
0.8
0
0.019608
awesome-app
702
2024-05-12T22:19:57.388244
BSD-3-Clause
true
44dca20638db11aed741c4a80679f744
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\test_overlaps.cpython-313.pyc
test_overlaps.cpython-313.pyc
Other
3,856
0.8
0.03125
0
vue-tools
876
2023-07-11T21:15:46.155098
Apache-2.0
true
4d6a36f516f3cf36527c2febc2b0e34d
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\interval\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
203
0.7
0
0
vue-tools
595
2025-01-16T15:48:51.074735
GPL-3.0
true
c4210a7de9b761c715fe518211210b18
from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs.period import IncompatibleFrequency\n\nfrom pandas import (\n NaT,\n Period,\n Timedelta,\n Timestamp,\n offsets,\n)\n\n\nclass TestPeriodArithmetic:\n def test_add_overflow_raises(self):\n # GH#55503\n per = Timestamp.max.to_period("ns")\n\n msg = "|".join(\n [\n "Python int too large to convert to C long",\n # windows, 32bit linux builds\n "int too big to convert",\n ]\n )\n with pytest.raises(OverflowError, match=msg):\n per + 1\n\n msg = "value too large"\n with pytest.raises(OverflowError, match=msg):\n per + Timedelta(1)\n with pytest.raises(OverflowError, match=msg):\n per + offsets.Nano(1)\n\n def test_period_add_integer(self):\n per1 = Period(freq="D", year=2008, month=1, day=1)\n per2 = Period(freq="D", year=2008, month=1, day=2)\n assert per1 + 1 == per2\n assert 1 + per1 == per2\n\n def test_period_add_invalid(self):\n # GH#4731\n per1 = Period(freq="D", year=2008, month=1, day=1)\n per2 = Period(freq="D", year=2008, month=1, day=2)\n\n msg = "|".join(\n [\n r"unsupported operand type\(s\)",\n "can only concatenate str",\n "must be str, not Period",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n per1 + "str"\n with pytest.raises(TypeError, match=msg):\n "str" + per1\n with pytest.raises(TypeError, match=msg):\n per1 + per2\n\n def test_period_sub_period_annual(self):\n left, right = Period("2011", freq="Y"), Period("2007", freq="Y")\n result = left - right\n assert result == 4 * right.freq\n\n msg = r"Input has different freq=M from Period\(freq=Y-DEC\)"\n with pytest.raises(IncompatibleFrequency, match=msg):\n left - Period("2007-01", freq="M")\n\n def test_period_sub_period(self):\n per1 = Period("2011-01-01", freq="D")\n per2 = Period("2011-01-15", freq="D")\n\n off = per1.freq\n assert per1 - per2 == -14 * off\n assert per2 - per1 == 14 * off\n\n msg = r"Input has different freq=M from Period\(freq=D\)"\n with pytest.raises(IncompatibleFrequency, match=msg):\n per1 - Period("2011-02", freq="M")\n\n @pytest.mark.parametrize("n", [1, 2, 3, 4])\n def test_sub_n_gt_1_ticks(self, tick_classes, n):\n # GH#23878\n p1 = Period("19910905", freq=tick_classes(n))\n p2 = Period("19920406", freq=tick_classes(n))\n\n expected = Period(str(p2), freq=p2.freq.base) - Period(\n str(p1), freq=p1.freq.base\n )\n\n assert (p2 - p1) == expected\n\n @pytest.mark.parametrize("normalize", [True, False])\n @pytest.mark.parametrize("n", [1, 2, 3, 4])\n @pytest.mark.parametrize(\n "offset, kwd_name",\n [\n (offsets.YearEnd, "month"),\n (offsets.QuarterEnd, "startingMonth"),\n (offsets.MonthEnd, None),\n (offsets.Week, "weekday"),\n ],\n )\n def test_sub_n_gt_1_offsets(self, offset, kwd_name, n, normalize):\n # GH#23878\n kwds = {kwd_name: 3} if kwd_name is not None else {}\n p1_d = "19910905"\n p2_d = "19920406"\n p1 = Period(p1_d, freq=offset(n, normalize, **kwds))\n p2 = Period(p2_d, freq=offset(n, normalize, **kwds))\n\n expected = Period(p2_d, freq=p2.freq.base) - Period(p1_d, freq=p1.freq.base)\n\n assert (p2 - p1) == expected\n\n def test_period_add_offset(self):\n # freq is DateOffset\n for freq in ["Y", "2Y", "3Y"]:\n per = Period("2011", freq=freq)\n exp = Period("2013", freq=freq)\n assert per + offsets.YearEnd(2) == exp\n assert offsets.YearEnd(2) + per == exp\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(365, "D"),\n timedelta(365),\n ]:\n msg = "Input has different freq|Input cannot be converted to Period"\n with pytest.raises(IncompatibleFrequency, match=msg):\n per + off\n with pytest.raises(IncompatibleFrequency, match=msg):\n off + per\n\n for freq in ["M", "2M", "3M"]:\n per = Period("2011-03", freq=freq)\n exp = Period("2011-05", freq=freq)\n assert per + offsets.MonthEnd(2) == exp\n assert offsets.MonthEnd(2) + per == exp\n\n exp = Period("2012-03", freq=freq)\n assert per + offsets.MonthEnd(12) == exp\n assert offsets.MonthEnd(12) + per == exp\n\n msg = "|".join(\n [\n "Input has different freq",\n "Input cannot be converted to Period",\n ]\n )\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(365, "D"),\n timedelta(365),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per + off\n with pytest.raises(IncompatibleFrequency, match=msg):\n off + per\n\n # freq is Tick\n for freq in ["D", "2D", "3D"]:\n per = Period("2011-04-01", freq=freq)\n\n exp = Period("2011-04-06", freq=freq)\n assert per + offsets.Day(5) == exp\n assert offsets.Day(5) + per == exp\n\n exp = Period("2011-04-02", freq=freq)\n assert per + offsets.Hour(24) == exp\n assert offsets.Hour(24) + per == exp\n\n exp = Period("2011-04-03", freq=freq)\n assert per + np.timedelta64(2, "D") == exp\n assert np.timedelta64(2, "D") + per == exp\n\n exp = Period("2011-04-02", freq=freq)\n assert per + np.timedelta64(3600 * 24, "s") == exp\n assert np.timedelta64(3600 * 24, "s") + per == exp\n\n exp = Period("2011-03-30", freq=freq)\n assert per + timedelta(-2) == exp\n assert timedelta(-2) + per == exp\n\n exp = Period("2011-04-03", freq=freq)\n assert per + timedelta(hours=48) == exp\n assert timedelta(hours=48) + per == exp\n\n msg = "|".join(\n [\n "Input has different freq",\n "Input cannot be converted to Period",\n ]\n )\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(4, "h"),\n timedelta(hours=23),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per + off\n with pytest.raises(IncompatibleFrequency, match=msg):\n off + per\n\n for freq in ["h", "2h", "3h"]:\n per = Period("2011-04-01 09:00", freq=freq)\n\n exp = Period("2011-04-03 09:00", freq=freq)\n assert per + offsets.Day(2) == exp\n assert offsets.Day(2) + per == exp\n\n exp = Period("2011-04-01 12:00", freq=freq)\n assert per + offsets.Hour(3) == exp\n assert offsets.Hour(3) + per == exp\n\n msg = "cannot use operands with types"\n exp = Period("2011-04-01 12:00", freq=freq)\n assert per + np.timedelta64(3, "h") == exp\n assert np.timedelta64(3, "h") + per == exp\n\n exp = Period("2011-04-01 10:00", freq=freq)\n assert per + np.timedelta64(3600, "s") == exp\n assert np.timedelta64(3600, "s") + per == exp\n\n exp = Period("2011-04-01 11:00", freq=freq)\n assert per + timedelta(minutes=120) == exp\n assert timedelta(minutes=120) + per == exp\n\n exp = Period("2011-04-05 12:00", freq=freq)\n assert per + timedelta(days=4, minutes=180) == exp\n assert timedelta(days=4, minutes=180) + per == exp\n\n msg = "|".join(\n [\n "Input has different freq",\n "Input cannot be converted to Period",\n ]\n )\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(3200, "s"),\n timedelta(hours=23, minutes=30),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per + off\n with pytest.raises(IncompatibleFrequency, match=msg):\n off + per\n\n def test_period_sub_offset(self):\n # freq is DateOffset\n msg = "|".join(\n [\n "Input has different freq",\n "Input cannot be converted to Period",\n ]\n )\n\n for freq in ["Y", "2Y", "3Y"]:\n per = Period("2011", freq=freq)\n assert per - offsets.YearEnd(2) == Period("2009", freq=freq)\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(365, "D"),\n timedelta(365),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per - off\n\n for freq in ["M", "2M", "3M"]:\n per = Period("2011-03", freq=freq)\n assert per - offsets.MonthEnd(2) == Period("2011-01", freq=freq)\n assert per - offsets.MonthEnd(12) == Period("2010-03", freq=freq)\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(365, "D"),\n timedelta(365),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per - off\n\n # freq is Tick\n for freq in ["D", "2D", "3D"]:\n per = Period("2011-04-01", freq=freq)\n assert per - offsets.Day(5) == Period("2011-03-27", freq=freq)\n assert per - offsets.Hour(24) == Period("2011-03-31", freq=freq)\n assert per - np.timedelta64(2, "D") == Period("2011-03-30", freq=freq)\n assert per - np.timedelta64(3600 * 24, "s") == Period(\n "2011-03-31", freq=freq\n )\n assert per - timedelta(-2) == Period("2011-04-03", freq=freq)\n assert per - timedelta(hours=48) == Period("2011-03-30", freq=freq)\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(4, "h"),\n timedelta(hours=23),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per - off\n\n for freq in ["h", "2h", "3h"]:\n per = Period("2011-04-01 09:00", freq=freq)\n assert per - offsets.Day(2) == Period("2011-03-30 09:00", freq=freq)\n assert per - offsets.Hour(3) == Period("2011-04-01 06:00", freq=freq)\n assert per - np.timedelta64(3, "h") == Period("2011-04-01 06:00", freq=freq)\n assert per - np.timedelta64(3600, "s") == Period(\n "2011-04-01 08:00", freq=freq\n )\n assert per - timedelta(minutes=120) == Period("2011-04-01 07:00", freq=freq)\n assert per - timedelta(days=4, minutes=180) == Period(\n "2011-03-28 06:00", freq=freq\n )\n\n for off in [\n offsets.YearBegin(2),\n offsets.MonthBegin(1),\n offsets.Minute(),\n np.timedelta64(3200, "s"),\n timedelta(hours=23, minutes=30),\n ]:\n with pytest.raises(IncompatibleFrequency, match=msg):\n per - off\n\n @pytest.mark.parametrize("freq", ["M", "2M", "3M"])\n def test_period_addsub_nat(self, freq):\n # GH#13071\n per = Period("2011-01", freq=freq)\n\n # For subtraction, NaT is treated as another Period object\n assert NaT - per is NaT\n assert per - NaT is NaT\n\n # For addition, NaT is treated as offset-like\n assert NaT + per is NaT\n assert per + NaT is NaT\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "m"])\n def test_period_add_sub_td64_nat(self, unit):\n # GH#47196\n per = Period("2022-06-01", "D")\n nat = np.timedelta64("NaT", unit)\n\n assert per + nat is NaT\n assert nat + per is NaT\n assert per - nat is NaT\n\n with pytest.raises(TypeError, match="unsupported operand"):\n nat - per\n\n def test_period_ops_offset(self):\n per = Period("2011-04-01", freq="D")\n result = per + offsets.Day()\n exp = Period("2011-04-02", freq="D")\n assert result == exp\n\n result = per - offsets.Day(2)\n exp = Period("2011-03-30", freq="D")\n assert result == exp\n\n msg = r"Input cannot be converted to Period\(freq=D\)"\n with pytest.raises(IncompatibleFrequency, match=msg):\n per + offsets.Hour(2)\n\n with pytest.raises(IncompatibleFrequency, match=msg):\n per - offsets.Hour(2)\n\n def test_period_add_timestamp_raises(self):\n # GH#17983\n ts = Timestamp("2017")\n per = Period("2017", freq="M")\n\n msg = r"unsupported operand type\(s\) for \+: 'Timestamp' and 'Period'"\n with pytest.raises(TypeError, match=msg):\n ts + per\n\n msg = r"unsupported operand type\(s\) for \+: 'Period' and 'Timestamp'"\n with pytest.raises(TypeError, match=msg):\n per + ts\n\n\nclass TestPeriodComparisons:\n def test_period_comparison_same_freq(self):\n jan = Period("2000-01", "M")\n feb = Period("2000-02", "M")\n\n assert not jan == feb\n assert jan != feb\n assert jan < feb\n assert jan <= feb\n assert not jan > feb\n assert not jan >= feb\n\n def test_period_comparison_same_period_different_object(self):\n # Separate Period objects for the same period\n left = Period("2000-01", "M")\n right = Period("2000-01", "M")\n\n assert left == right\n assert left >= right\n assert left <= right\n assert not left < right\n assert not left > right\n\n def test_period_comparison_mismatched_freq(self):\n jan = Period("2000-01", "M")\n day = Period("2012-01-01", "D")\n\n assert not jan == day\n assert jan != day\n msg = r"Input has different freq=D from Period\(freq=M\)"\n with pytest.raises(IncompatibleFrequency, match=msg):\n jan < day\n with pytest.raises(IncompatibleFrequency, match=msg):\n jan <= day\n with pytest.raises(IncompatibleFrequency, match=msg):\n jan > day\n with pytest.raises(IncompatibleFrequency, match=msg):\n jan >= day\n\n def test_period_comparison_invalid_type(self):\n jan = Period("2000-01", "M")\n\n assert not jan == 1\n assert jan != 1\n\n int_or_per = "'(Period|int)'"\n msg = f"not supported between instances of {int_or_per} and {int_or_per}"\n for left, right in [(jan, 1), (1, jan)]:\n with pytest.raises(TypeError, match=msg):\n left > right\n with pytest.raises(TypeError, match=msg):\n left >= right\n with pytest.raises(TypeError, match=msg):\n left < right\n with pytest.raises(TypeError, match=msg):\n left <= right\n\n def test_period_comparison_nat(self):\n per = Period("2011-01-01", freq="D")\n\n ts = Timestamp("2011-01-01")\n # confirm Period('NaT') work identical with Timestamp('NaT')\n for left, right in [\n (NaT, per),\n (per, NaT),\n (NaT, ts),\n (ts, NaT),\n ]:\n assert not left < right\n assert not left > right\n assert not left == right\n assert left != right\n assert not left <= right\n assert not left >= right\n\n @pytest.mark.parametrize(\n "zerodim_arr, expected",\n ((np.array(0), False), (np.array(Period("2000-01", "M")), True)),\n )\n def test_period_comparison_numpy_zerodim_arr(self, zerodim_arr, expected):\n per = Period("2000-01", "M")\n\n assert (per == zerodim_arr) is expected\n assert (zerodim_arr == per) is expected\n
.venv\Lib\site-packages\pandas\tests\scalar\period\test_arithmetic.py
test_arithmetic.py
Python
16,775
0.95
0.088477
0.039506
awesome-app
70
2023-11-09T17:32:47.955057
GPL-3.0
true
5be43614a75c4cb8995120750f1a2a89
import pytest\n\nfrom pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\nfrom pandas.errors import OutOfBoundsDatetime\n\nfrom pandas import (\n Period,\n Timestamp,\n offsets,\n)\nimport pandas._testing as tm\n\nbday_msg = "Period with BDay freq is deprecated"\n\n\nclass TestFreqConversion:\n """Test frequency conversion of date objects"""\n\n @pytest.mark.filterwarnings("ignore:Period with BDay:FutureWarning")\n @pytest.mark.parametrize("freq", ["Y", "Q", "M", "W", "B", "D"])\n def test_asfreq_near_zero(self, freq):\n # GH#19643, GH#19650\n per = Period("0001-01-01", freq=freq)\n tup1 = (per.year, per.hour, per.day)\n\n prev = per - 1\n assert prev.ordinal == per.ordinal - 1\n tup2 = (prev.year, prev.month, prev.day)\n assert tup2 < tup1\n\n def test_asfreq_near_zero_weekly(self):\n # GH#19834\n per1 = Period("0001-01-01", "D") + 6\n per2 = Period("0001-01-01", "D") - 6\n week1 = per1.asfreq("W")\n week2 = per2.asfreq("W")\n assert week1 != week2\n assert week1.asfreq("D", "E") >= per1\n assert week2.asfreq("D", "S") <= per2\n\n def test_to_timestamp_out_of_bounds(self):\n # GH#19643, used to incorrectly give Timestamp in 1754\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per = Period("0001-01-01", freq="B")\n msg = "Out of bounds nanosecond timestamp"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per.to_timestamp()\n\n def test_asfreq_corner(self):\n val = Period(freq="Y", year=2007)\n result1 = val.asfreq("5min")\n result2 = val.asfreq("min")\n expected = Period("2007-12-31 23:59", freq="min")\n assert result1.ordinal == expected.ordinal\n assert result1.freqstr == "5min"\n assert result2.ordinal == expected.ordinal\n assert result2.freqstr == "min"\n\n def test_conv_annual(self):\n # frequency conversion tests: from Annual Frequency\n\n ival_A = Period(freq="Y", year=2007)\n\n ival_AJAN = Period(freq="Y-JAN", year=2007)\n ival_AJUN = Period(freq="Y-JUN", year=2007)\n ival_ANOV = Period(freq="Y-NOV", year=2007)\n\n ival_A_to_Q_start = Period(freq="Q", year=2007, quarter=1)\n ival_A_to_Q_end = Period(freq="Q", year=2007, quarter=4)\n ival_A_to_M_start = Period(freq="M", year=2007, month=1)\n ival_A_to_M_end = Period(freq="M", year=2007, month=12)\n ival_A_to_W_start = Period(freq="W", year=2007, month=1, day=1)\n ival_A_to_W_end = Period(freq="W", year=2007, month=12, day=31)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_A_to_B_start = Period(freq="B", year=2007, month=1, day=1)\n ival_A_to_B_end = Period(freq="B", year=2007, month=12, day=31)\n ival_A_to_D_start = Period(freq="D", year=2007, month=1, day=1)\n ival_A_to_D_end = Period(freq="D", year=2007, month=12, day=31)\n ival_A_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_A_to_H_end = Period(freq="h", year=2007, month=12, day=31, hour=23)\n ival_A_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_A_to_T_end = Period(\n freq="Min", year=2007, month=12, day=31, hour=23, minute=59\n )\n ival_A_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_A_to_S_end = Period(\n freq="s", year=2007, month=12, day=31, hour=23, minute=59, second=59\n )\n\n ival_AJAN_to_D_end = Period(freq="D", year=2007, month=1, day=31)\n ival_AJAN_to_D_start = Period(freq="D", year=2006, month=2, day=1)\n ival_AJUN_to_D_end = Period(freq="D", year=2007, month=6, day=30)\n ival_AJUN_to_D_start = Period(freq="D", year=2006, month=7, day=1)\n ival_ANOV_to_D_end = Period(freq="D", year=2007, month=11, day=30)\n ival_ANOV_to_D_start = Period(freq="D", year=2006, month=12, day=1)\n\n assert ival_A.asfreq("Q", "s") == ival_A_to_Q_start\n assert ival_A.asfreq("Q", "e") == ival_A_to_Q_end\n assert ival_A.asfreq("M", "s") == ival_A_to_M_start\n assert ival_A.asfreq("M", "E") == ival_A_to_M_end\n assert ival_A.asfreq("W", "s") == ival_A_to_W_start\n assert ival_A.asfreq("W", "E") == ival_A_to_W_end\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_A.asfreq("B", "s") == ival_A_to_B_start\n assert ival_A.asfreq("B", "E") == ival_A_to_B_end\n assert ival_A.asfreq("D", "s") == ival_A_to_D_start\n assert ival_A.asfreq("D", "E") == ival_A_to_D_end\n msg = "'H' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert ival_A.asfreq("H", "s") == ival_A_to_H_start\n assert ival_A.asfreq("H", "E") == ival_A_to_H_end\n assert ival_A.asfreq("min", "s") == ival_A_to_T_start\n assert ival_A.asfreq("min", "E") == ival_A_to_T_end\n msg = "'T' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert ival_A.asfreq("T", "s") == ival_A_to_T_start\n assert ival_A.asfreq("T", "E") == ival_A_to_T_end\n msg = "'S' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n assert ival_A.asfreq("S", "S") == ival_A_to_S_start\n assert ival_A.asfreq("S", "E") == ival_A_to_S_end\n\n assert ival_AJAN.asfreq("D", "s") == ival_AJAN_to_D_start\n assert ival_AJAN.asfreq("D", "E") == ival_AJAN_to_D_end\n\n assert ival_AJUN.asfreq("D", "s") == ival_AJUN_to_D_start\n assert ival_AJUN.asfreq("D", "E") == ival_AJUN_to_D_end\n\n assert ival_ANOV.asfreq("D", "s") == ival_ANOV_to_D_start\n assert ival_ANOV.asfreq("D", "E") == ival_ANOV_to_D_end\n\n assert ival_A.asfreq("Y") == ival_A\n\n def test_conv_quarterly(self):\n # frequency conversion tests: from Quarterly Frequency\n\n ival_Q = Period(freq="Q", year=2007, quarter=1)\n ival_Q_end_of_year = Period(freq="Q", year=2007, quarter=4)\n\n ival_QEJAN = Period(freq="Q-JAN", year=2007, quarter=1)\n ival_QEJUN = Period(freq="Q-JUN", year=2007, quarter=1)\n\n ival_Q_to_A = Period(freq="Y", year=2007)\n ival_Q_to_M_start = Period(freq="M", year=2007, month=1)\n ival_Q_to_M_end = Period(freq="M", year=2007, month=3)\n ival_Q_to_W_start = Period(freq="W", year=2007, month=1, day=1)\n ival_Q_to_W_end = Period(freq="W", year=2007, month=3, day=31)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_Q_to_B_start = Period(freq="B", year=2007, month=1, day=1)\n ival_Q_to_B_end = Period(freq="B", year=2007, month=3, day=30)\n ival_Q_to_D_start = Period(freq="D", year=2007, month=1, day=1)\n ival_Q_to_D_end = Period(freq="D", year=2007, month=3, day=31)\n ival_Q_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_Q_to_H_end = Period(freq="h", year=2007, month=3, day=31, hour=23)\n ival_Q_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_Q_to_T_end = Period(\n freq="Min", year=2007, month=3, day=31, hour=23, minute=59\n )\n ival_Q_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_Q_to_S_end = Period(\n freq="s", year=2007, month=3, day=31, hour=23, minute=59, second=59\n )\n\n ival_QEJAN_to_D_start = Period(freq="D", year=2006, month=2, day=1)\n ival_QEJAN_to_D_end = Period(freq="D", year=2006, month=4, day=30)\n\n ival_QEJUN_to_D_start = Period(freq="D", year=2006, month=7, day=1)\n ival_QEJUN_to_D_end = Period(freq="D", year=2006, month=9, day=30)\n\n assert ival_Q.asfreq("Y") == ival_Q_to_A\n assert ival_Q_end_of_year.asfreq("Y") == ival_Q_to_A\n\n assert ival_Q.asfreq("M", "s") == ival_Q_to_M_start\n assert ival_Q.asfreq("M", "E") == ival_Q_to_M_end\n assert ival_Q.asfreq("W", "s") == ival_Q_to_W_start\n assert ival_Q.asfreq("W", "E") == ival_Q_to_W_end\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_Q.asfreq("B", "s") == ival_Q_to_B_start\n assert ival_Q.asfreq("B", "E") == ival_Q_to_B_end\n assert ival_Q.asfreq("D", "s") == ival_Q_to_D_start\n assert ival_Q.asfreq("D", "E") == ival_Q_to_D_end\n assert ival_Q.asfreq("h", "s") == ival_Q_to_H_start\n assert ival_Q.asfreq("h", "E") == ival_Q_to_H_end\n assert ival_Q.asfreq("Min", "s") == ival_Q_to_T_start\n assert ival_Q.asfreq("Min", "E") == ival_Q_to_T_end\n assert ival_Q.asfreq("s", "s") == ival_Q_to_S_start\n assert ival_Q.asfreq("s", "E") == ival_Q_to_S_end\n\n assert ival_QEJAN.asfreq("D", "s") == ival_QEJAN_to_D_start\n assert ival_QEJAN.asfreq("D", "E") == ival_QEJAN_to_D_end\n assert ival_QEJUN.asfreq("D", "s") == ival_QEJUN_to_D_start\n assert ival_QEJUN.asfreq("D", "E") == ival_QEJUN_to_D_end\n\n assert ival_Q.asfreq("Q") == ival_Q\n\n def test_conv_monthly(self):\n # frequency conversion tests: from Monthly Frequency\n\n ival_M = Period(freq="M", year=2007, month=1)\n ival_M_end_of_year = Period(freq="M", year=2007, month=12)\n ival_M_end_of_quarter = Period(freq="M", year=2007, month=3)\n ival_M_to_A = Period(freq="Y", year=2007)\n ival_M_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_M_to_W_start = Period(freq="W", year=2007, month=1, day=1)\n ival_M_to_W_end = Period(freq="W", year=2007, month=1, day=31)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_M_to_B_start = Period(freq="B", year=2007, month=1, day=1)\n ival_M_to_B_end = Period(freq="B", year=2007, month=1, day=31)\n ival_M_to_D_start = Period(freq="D", year=2007, month=1, day=1)\n ival_M_to_D_end = Period(freq="D", year=2007, month=1, day=31)\n ival_M_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_M_to_H_end = Period(freq="h", year=2007, month=1, day=31, hour=23)\n ival_M_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_M_to_T_end = Period(\n freq="Min", year=2007, month=1, day=31, hour=23, minute=59\n )\n ival_M_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_M_to_S_end = Period(\n freq="s", year=2007, month=1, day=31, hour=23, minute=59, second=59\n )\n\n assert ival_M.asfreq("Y") == ival_M_to_A\n assert ival_M_end_of_year.asfreq("Y") == ival_M_to_A\n assert ival_M.asfreq("Q") == ival_M_to_Q\n assert ival_M_end_of_quarter.asfreq("Q") == ival_M_to_Q\n\n assert ival_M.asfreq("W", "s") == ival_M_to_W_start\n assert ival_M.asfreq("W", "E") == ival_M_to_W_end\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_M.asfreq("B", "s") == ival_M_to_B_start\n assert ival_M.asfreq("B", "E") == ival_M_to_B_end\n assert ival_M.asfreq("D", "s") == ival_M_to_D_start\n assert ival_M.asfreq("D", "E") == ival_M_to_D_end\n assert ival_M.asfreq("h", "s") == ival_M_to_H_start\n assert ival_M.asfreq("h", "E") == ival_M_to_H_end\n assert ival_M.asfreq("Min", "s") == ival_M_to_T_start\n assert ival_M.asfreq("Min", "E") == ival_M_to_T_end\n assert ival_M.asfreq("s", "s") == ival_M_to_S_start\n assert ival_M.asfreq("s", "E") == ival_M_to_S_end\n\n assert ival_M.asfreq("M") == ival_M\n\n def test_conv_weekly(self):\n # frequency conversion tests: from Weekly Frequency\n ival_W = Period(freq="W", year=2007, month=1, day=1)\n\n ival_WSUN = Period(freq="W", year=2007, month=1, day=7)\n ival_WSAT = Period(freq="W-SAT", year=2007, month=1, day=6)\n ival_WFRI = Period(freq="W-FRI", year=2007, month=1, day=5)\n ival_WTHU = Period(freq="W-THU", year=2007, month=1, day=4)\n ival_WWED = Period(freq="W-WED", year=2007, month=1, day=3)\n ival_WTUE = Period(freq="W-TUE", year=2007, month=1, day=2)\n ival_WMON = Period(freq="W-MON", year=2007, month=1, day=1)\n\n ival_WSUN_to_D_start = Period(freq="D", year=2007, month=1, day=1)\n ival_WSUN_to_D_end = Period(freq="D", year=2007, month=1, day=7)\n ival_WSAT_to_D_start = Period(freq="D", year=2006, month=12, day=31)\n ival_WSAT_to_D_end = Period(freq="D", year=2007, month=1, day=6)\n ival_WFRI_to_D_start = Period(freq="D", year=2006, month=12, day=30)\n ival_WFRI_to_D_end = Period(freq="D", year=2007, month=1, day=5)\n ival_WTHU_to_D_start = Period(freq="D", year=2006, month=12, day=29)\n ival_WTHU_to_D_end = Period(freq="D", year=2007, month=1, day=4)\n ival_WWED_to_D_start = Period(freq="D", year=2006, month=12, day=28)\n ival_WWED_to_D_end = Period(freq="D", year=2007, month=1, day=3)\n ival_WTUE_to_D_start = Period(freq="D", year=2006, month=12, day=27)\n ival_WTUE_to_D_end = Period(freq="D", year=2007, month=1, day=2)\n ival_WMON_to_D_start = Period(freq="D", year=2006, month=12, day=26)\n ival_WMON_to_D_end = Period(freq="D", year=2007, month=1, day=1)\n\n ival_W_end_of_year = Period(freq="W", year=2007, month=12, day=31)\n ival_W_end_of_quarter = Period(freq="W", year=2007, month=3, day=31)\n ival_W_end_of_month = Period(freq="W", year=2007, month=1, day=31)\n ival_W_to_A = Period(freq="Y", year=2007)\n ival_W_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_W_to_M = Period(freq="M", year=2007, month=1)\n\n if Period(freq="D", year=2007, month=12, day=31).weekday == 6:\n ival_W_to_A_end_of_year = Period(freq="Y", year=2007)\n else:\n ival_W_to_A_end_of_year = Period(freq="Y", year=2008)\n\n if Period(freq="D", year=2007, month=3, day=31).weekday == 6:\n ival_W_to_Q_end_of_quarter = Period(freq="Q", year=2007, quarter=1)\n else:\n ival_W_to_Q_end_of_quarter = Period(freq="Q", year=2007, quarter=2)\n\n if Period(freq="D", year=2007, month=1, day=31).weekday == 6:\n ival_W_to_M_end_of_month = Period(freq="M", year=2007, month=1)\n else:\n ival_W_to_M_end_of_month = Period(freq="M", year=2007, month=2)\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_W_to_B_start = Period(freq="B", year=2007, month=1, day=1)\n ival_W_to_B_end = Period(freq="B", year=2007, month=1, day=5)\n ival_W_to_D_start = Period(freq="D", year=2007, month=1, day=1)\n ival_W_to_D_end = Period(freq="D", year=2007, month=1, day=7)\n ival_W_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_W_to_H_end = Period(freq="h", year=2007, month=1, day=7, hour=23)\n ival_W_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_W_to_T_end = Period(\n freq="Min", year=2007, month=1, day=7, hour=23, minute=59\n )\n ival_W_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_W_to_S_end = Period(\n freq="s", year=2007, month=1, day=7, hour=23, minute=59, second=59\n )\n\n assert ival_W.asfreq("Y") == ival_W_to_A\n assert ival_W_end_of_year.asfreq("Y") == ival_W_to_A_end_of_year\n\n assert ival_W.asfreq("Q") == ival_W_to_Q\n assert ival_W_end_of_quarter.asfreq("Q") == ival_W_to_Q_end_of_quarter\n\n assert ival_W.asfreq("M") == ival_W_to_M\n assert ival_W_end_of_month.asfreq("M") == ival_W_to_M_end_of_month\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_W.asfreq("B", "s") == ival_W_to_B_start\n assert ival_W.asfreq("B", "E") == ival_W_to_B_end\n\n assert ival_W.asfreq("D", "s") == ival_W_to_D_start\n assert ival_W.asfreq("D", "E") == ival_W_to_D_end\n\n assert ival_WSUN.asfreq("D", "s") == ival_WSUN_to_D_start\n assert ival_WSUN.asfreq("D", "E") == ival_WSUN_to_D_end\n assert ival_WSAT.asfreq("D", "s") == ival_WSAT_to_D_start\n assert ival_WSAT.asfreq("D", "E") == ival_WSAT_to_D_end\n assert ival_WFRI.asfreq("D", "s") == ival_WFRI_to_D_start\n assert ival_WFRI.asfreq("D", "E") == ival_WFRI_to_D_end\n assert ival_WTHU.asfreq("D", "s") == ival_WTHU_to_D_start\n assert ival_WTHU.asfreq("D", "E") == ival_WTHU_to_D_end\n assert ival_WWED.asfreq("D", "s") == ival_WWED_to_D_start\n assert ival_WWED.asfreq("D", "E") == ival_WWED_to_D_end\n assert ival_WTUE.asfreq("D", "s") == ival_WTUE_to_D_start\n assert ival_WTUE.asfreq("D", "E") == ival_WTUE_to_D_end\n assert ival_WMON.asfreq("D", "s") == ival_WMON_to_D_start\n assert ival_WMON.asfreq("D", "E") == ival_WMON_to_D_end\n\n assert ival_W.asfreq("h", "s") == ival_W_to_H_start\n assert ival_W.asfreq("h", "E") == ival_W_to_H_end\n assert ival_W.asfreq("Min", "s") == ival_W_to_T_start\n assert ival_W.asfreq("Min", "E") == ival_W_to_T_end\n assert ival_W.asfreq("s", "s") == ival_W_to_S_start\n assert ival_W.asfreq("s", "E") == ival_W_to_S_end\n\n assert ival_W.asfreq("W") == ival_W\n\n msg = INVALID_FREQ_ERR_MSG\n with pytest.raises(ValueError, match=msg):\n ival_W.asfreq("WK")\n\n def test_conv_weekly_legacy(self):\n # frequency conversion tests: from Weekly Frequency\n msg = INVALID_FREQ_ERR_MSG\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK", year=2007, month=1, day=1)\n\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-SAT", year=2007, month=1, day=6)\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-FRI", year=2007, month=1, day=5)\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-THU", year=2007, month=1, day=4)\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-WED", year=2007, month=1, day=3)\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-TUE", year=2007, month=1, day=2)\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK-MON", year=2007, month=1, day=1)\n\n def test_conv_business(self):\n # frequency conversion tests: from Business Frequency"\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_B = Period(freq="B", year=2007, month=1, day=1)\n ival_B_end_of_year = Period(freq="B", year=2007, month=12, day=31)\n ival_B_end_of_quarter = Period(freq="B", year=2007, month=3, day=30)\n ival_B_end_of_month = Period(freq="B", year=2007, month=1, day=31)\n ival_B_end_of_week = Period(freq="B", year=2007, month=1, day=5)\n\n ival_B_to_A = Period(freq="Y", year=2007)\n ival_B_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_B_to_M = Period(freq="M", year=2007, month=1)\n ival_B_to_W = Period(freq="W", year=2007, month=1, day=7)\n ival_B_to_D = Period(freq="D", year=2007, month=1, day=1)\n ival_B_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_B_to_H_end = Period(freq="h", year=2007, month=1, day=1, hour=23)\n ival_B_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_B_to_T_end = Period(\n freq="Min", year=2007, month=1, day=1, hour=23, minute=59\n )\n ival_B_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_B_to_S_end = Period(\n freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59\n )\n\n assert ival_B.asfreq("Y") == ival_B_to_A\n assert ival_B_end_of_year.asfreq("Y") == ival_B_to_A\n assert ival_B.asfreq("Q") == ival_B_to_Q\n assert ival_B_end_of_quarter.asfreq("Q") == ival_B_to_Q\n assert ival_B.asfreq("M") == ival_B_to_M\n assert ival_B_end_of_month.asfreq("M") == ival_B_to_M\n assert ival_B.asfreq("W") == ival_B_to_W\n assert ival_B_end_of_week.asfreq("W") == ival_B_to_W\n\n assert ival_B.asfreq("D") == ival_B_to_D\n\n assert ival_B.asfreq("h", "s") == ival_B_to_H_start\n assert ival_B.asfreq("h", "E") == ival_B_to_H_end\n assert ival_B.asfreq("Min", "s") == ival_B_to_T_start\n assert ival_B.asfreq("Min", "E") == ival_B_to_T_end\n assert ival_B.asfreq("s", "s") == ival_B_to_S_start\n assert ival_B.asfreq("s", "E") == ival_B_to_S_end\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_B.asfreq("B") == ival_B\n\n def test_conv_daily(self):\n # frequency conversion tests: from Business Frequency"\n\n ival_D = Period(freq="D", year=2007, month=1, day=1)\n ival_D_end_of_year = Period(freq="D", year=2007, month=12, day=31)\n ival_D_end_of_quarter = Period(freq="D", year=2007, month=3, day=31)\n ival_D_end_of_month = Period(freq="D", year=2007, month=1, day=31)\n ival_D_end_of_week = Period(freq="D", year=2007, month=1, day=7)\n\n ival_D_friday = Period(freq="D", year=2007, month=1, day=5)\n ival_D_saturday = Period(freq="D", year=2007, month=1, day=6)\n ival_D_sunday = Period(freq="D", year=2007, month=1, day=7)\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_B_friday = Period(freq="B", year=2007, month=1, day=5)\n ival_B_monday = Period(freq="B", year=2007, month=1, day=8)\n\n ival_D_to_A = Period(freq="Y", year=2007)\n\n ival_Deoq_to_AJAN = Period(freq="Y-JAN", year=2008)\n ival_Deoq_to_AJUN = Period(freq="Y-JUN", year=2007)\n ival_Deoq_to_ADEC = Period(freq="Y-DEC", year=2007)\n\n ival_D_to_QEJAN = Period(freq="Q-JAN", year=2007, quarter=4)\n ival_D_to_QEJUN = Period(freq="Q-JUN", year=2007, quarter=3)\n ival_D_to_QEDEC = Period(freq="Q-DEC", year=2007, quarter=1)\n\n ival_D_to_M = Period(freq="M", year=2007, month=1)\n ival_D_to_W = Period(freq="W", year=2007, month=1, day=7)\n\n ival_D_to_H_start = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_D_to_H_end = Period(freq="h", year=2007, month=1, day=1, hour=23)\n ival_D_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_D_to_T_end = Period(\n freq="Min", year=2007, month=1, day=1, hour=23, minute=59\n )\n ival_D_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_D_to_S_end = Period(\n freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59\n )\n\n assert ival_D.asfreq("Y") == ival_D_to_A\n\n assert ival_D_end_of_quarter.asfreq("Y-JAN") == ival_Deoq_to_AJAN\n assert ival_D_end_of_quarter.asfreq("Y-JUN") == ival_Deoq_to_AJUN\n assert ival_D_end_of_quarter.asfreq("Y-DEC") == ival_Deoq_to_ADEC\n\n assert ival_D_end_of_year.asfreq("Y") == ival_D_to_A\n assert ival_D_end_of_quarter.asfreq("Q") == ival_D_to_QEDEC\n assert ival_D.asfreq("Q-JAN") == ival_D_to_QEJAN\n assert ival_D.asfreq("Q-JUN") == ival_D_to_QEJUN\n assert ival_D.asfreq("Q-DEC") == ival_D_to_QEDEC\n assert ival_D.asfreq("M") == ival_D_to_M\n assert ival_D_end_of_month.asfreq("M") == ival_D_to_M\n assert ival_D.asfreq("W") == ival_D_to_W\n assert ival_D_end_of_week.asfreq("W") == ival_D_to_W\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_D_friday.asfreq("B") == ival_B_friday\n assert ival_D_saturday.asfreq("B", "s") == ival_B_friday\n assert ival_D_saturday.asfreq("B", "E") == ival_B_monday\n assert ival_D_sunday.asfreq("B", "s") == ival_B_friday\n assert ival_D_sunday.asfreq("B", "E") == ival_B_monday\n\n assert ival_D.asfreq("h", "s") == ival_D_to_H_start\n assert ival_D.asfreq("h", "E") == ival_D_to_H_end\n assert ival_D.asfreq("Min", "s") == ival_D_to_T_start\n assert ival_D.asfreq("Min", "E") == ival_D_to_T_end\n assert ival_D.asfreq("s", "s") == ival_D_to_S_start\n assert ival_D.asfreq("s", "E") == ival_D_to_S_end\n\n assert ival_D.asfreq("D") == ival_D\n\n def test_conv_hourly(self):\n # frequency conversion tests: from Hourly Frequency"\n\n ival_H = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_H_end_of_year = Period(freq="h", year=2007, month=12, day=31, hour=23)\n ival_H_end_of_quarter = Period(freq="h", year=2007, month=3, day=31, hour=23)\n ival_H_end_of_month = Period(freq="h", year=2007, month=1, day=31, hour=23)\n ival_H_end_of_week = Period(freq="h", year=2007, month=1, day=7, hour=23)\n ival_H_end_of_day = Period(freq="h", year=2007, month=1, day=1, hour=23)\n ival_H_end_of_bus = Period(freq="h", year=2007, month=1, day=1, hour=23)\n\n ival_H_to_A = Period(freq="Y", year=2007)\n ival_H_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_H_to_M = Period(freq="M", year=2007, month=1)\n ival_H_to_W = Period(freq="W", year=2007, month=1, day=7)\n ival_H_to_D = Period(freq="D", year=2007, month=1, day=1)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_H_to_B = Period(freq="B", year=2007, month=1, day=1)\n\n ival_H_to_T_start = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0\n )\n ival_H_to_T_end = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=59\n )\n ival_H_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_H_to_S_end = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=59, second=59\n )\n\n assert ival_H.asfreq("Y") == ival_H_to_A\n assert ival_H_end_of_year.asfreq("Y") == ival_H_to_A\n assert ival_H.asfreq("Q") == ival_H_to_Q\n assert ival_H_end_of_quarter.asfreq("Q") == ival_H_to_Q\n assert ival_H.asfreq("M") == ival_H_to_M\n assert ival_H_end_of_month.asfreq("M") == ival_H_to_M\n assert ival_H.asfreq("W") == ival_H_to_W\n assert ival_H_end_of_week.asfreq("W") == ival_H_to_W\n assert ival_H.asfreq("D") == ival_H_to_D\n assert ival_H_end_of_day.asfreq("D") == ival_H_to_D\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_H.asfreq("B") == ival_H_to_B\n assert ival_H_end_of_bus.asfreq("B") == ival_H_to_B\n\n assert ival_H.asfreq("Min", "s") == ival_H_to_T_start\n assert ival_H.asfreq("Min", "E") == ival_H_to_T_end\n assert ival_H.asfreq("s", "s") == ival_H_to_S_start\n assert ival_H.asfreq("s", "E") == ival_H_to_S_end\n\n assert ival_H.asfreq("h") == ival_H\n\n def test_conv_minutely(self):\n # frequency conversion tests: from Minutely Frequency"\n\n ival_T = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0)\n ival_T_end_of_year = Period(\n freq="Min", year=2007, month=12, day=31, hour=23, minute=59\n )\n ival_T_end_of_quarter = Period(\n freq="Min", year=2007, month=3, day=31, hour=23, minute=59\n )\n ival_T_end_of_month = Period(\n freq="Min", year=2007, month=1, day=31, hour=23, minute=59\n )\n ival_T_end_of_week = Period(\n freq="Min", year=2007, month=1, day=7, hour=23, minute=59\n )\n ival_T_end_of_day = Period(\n freq="Min", year=2007, month=1, day=1, hour=23, minute=59\n )\n ival_T_end_of_bus = Period(\n freq="Min", year=2007, month=1, day=1, hour=23, minute=59\n )\n ival_T_end_of_hour = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=59\n )\n\n ival_T_to_A = Period(freq="Y", year=2007)\n ival_T_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_T_to_M = Period(freq="M", year=2007, month=1)\n ival_T_to_W = Period(freq="W", year=2007, month=1, day=7)\n ival_T_to_D = Period(freq="D", year=2007, month=1, day=1)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_T_to_B = Period(freq="B", year=2007, month=1, day=1)\n ival_T_to_H = Period(freq="h", year=2007, month=1, day=1, hour=0)\n\n ival_T_to_S_start = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n ival_T_to_S_end = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=59\n )\n\n assert ival_T.asfreq("Y") == ival_T_to_A\n assert ival_T_end_of_year.asfreq("Y") == ival_T_to_A\n assert ival_T.asfreq("Q") == ival_T_to_Q\n assert ival_T_end_of_quarter.asfreq("Q") == ival_T_to_Q\n assert ival_T.asfreq("M") == ival_T_to_M\n assert ival_T_end_of_month.asfreq("M") == ival_T_to_M\n assert ival_T.asfreq("W") == ival_T_to_W\n assert ival_T_end_of_week.asfreq("W") == ival_T_to_W\n assert ival_T.asfreq("D") == ival_T_to_D\n assert ival_T_end_of_day.asfreq("D") == ival_T_to_D\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_T.asfreq("B") == ival_T_to_B\n assert ival_T_end_of_bus.asfreq("B") == ival_T_to_B\n assert ival_T.asfreq("h") == ival_T_to_H\n assert ival_T_end_of_hour.asfreq("h") == ival_T_to_H\n\n assert ival_T.asfreq("s", "s") == ival_T_to_S_start\n assert ival_T.asfreq("s", "E") == ival_T_to_S_end\n\n assert ival_T.asfreq("Min") == ival_T\n\n def test_conv_secondly(self):\n # frequency conversion tests: from Secondly Frequency"\n\n ival_S = Period(freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=0)\n ival_S_end_of_year = Period(\n freq="s", year=2007, month=12, day=31, hour=23, minute=59, second=59\n )\n ival_S_end_of_quarter = Period(\n freq="s", year=2007, month=3, day=31, hour=23, minute=59, second=59\n )\n ival_S_end_of_month = Period(\n freq="s", year=2007, month=1, day=31, hour=23, minute=59, second=59\n )\n ival_S_end_of_week = Period(\n freq="s", year=2007, month=1, day=7, hour=23, minute=59, second=59\n )\n ival_S_end_of_day = Period(\n freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59\n )\n ival_S_end_of_bus = Period(\n freq="s", year=2007, month=1, day=1, hour=23, minute=59, second=59\n )\n ival_S_end_of_hour = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=59, second=59\n )\n ival_S_end_of_minute = Period(\n freq="s", year=2007, month=1, day=1, hour=0, minute=0, second=59\n )\n\n ival_S_to_A = Period(freq="Y", year=2007)\n ival_S_to_Q = Period(freq="Q", year=2007, quarter=1)\n ival_S_to_M = Period(freq="M", year=2007, month=1)\n ival_S_to_W = Period(freq="W", year=2007, month=1, day=7)\n ival_S_to_D = Period(freq="D", year=2007, month=1, day=1)\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n ival_S_to_B = Period(freq="B", year=2007, month=1, day=1)\n ival_S_to_H = Period(freq="h", year=2007, month=1, day=1, hour=0)\n ival_S_to_T = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0)\n\n assert ival_S.asfreq("Y") == ival_S_to_A\n assert ival_S_end_of_year.asfreq("Y") == ival_S_to_A\n assert ival_S.asfreq("Q") == ival_S_to_Q\n assert ival_S_end_of_quarter.asfreq("Q") == ival_S_to_Q\n assert ival_S.asfreq("M") == ival_S_to_M\n assert ival_S_end_of_month.asfreq("M") == ival_S_to_M\n assert ival_S.asfreq("W") == ival_S_to_W\n assert ival_S_end_of_week.asfreq("W") == ival_S_to_W\n assert ival_S.asfreq("D") == ival_S_to_D\n assert ival_S_end_of_day.asfreq("D") == ival_S_to_D\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert ival_S.asfreq("B") == ival_S_to_B\n assert ival_S_end_of_bus.asfreq("B") == ival_S_to_B\n assert ival_S.asfreq("h") == ival_S_to_H\n assert ival_S_end_of_hour.asfreq("h") == ival_S_to_H\n assert ival_S.asfreq("Min") == ival_S_to_T\n assert ival_S_end_of_minute.asfreq("Min") == ival_S_to_T\n\n assert ival_S.asfreq("s") == ival_S\n\n def test_conv_microsecond(self):\n # GH#31475 Avoid floating point errors dropping the start_time to\n # before the beginning of the Period\n per = Period("2020-01-30 15:57:27.576166", freq="us")\n assert per.ordinal == 1580399847576166\n\n start = per.start_time\n expected = Timestamp("2020-01-30 15:57:27.576166")\n assert start == expected\n assert start._value == per.ordinal * 1000\n\n per2 = Period("2300-01-01", "us")\n msg = "2300-01-01"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n per2.start_time\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n per2.end_time\n\n def test_asfreq_mult(self):\n # normal freq to mult freq\n p = Period(freq="Y", year=2007)\n # ordinal will not change\n for freq in ["3Y", offsets.YearEnd(3)]:\n result = p.asfreq(freq)\n expected = Period("2007", freq="3Y")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n # ordinal will not change\n for freq in ["3Y", offsets.YearEnd(3)]:\n result = p.asfreq(freq, how="S")\n expected = Period("2007", freq="3Y")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n\n # mult freq to normal freq\n p = Period(freq="3Y", year=2007)\n # ordinal will change because how=E is the default\n for freq in ["Y", offsets.YearEnd()]:\n result = p.asfreq(freq)\n expected = Period("2009", freq="Y")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n # ordinal will not change\n for freq in ["Y", offsets.YearEnd()]:\n result = p.asfreq(freq, how="s")\n expected = Period("2007", freq="Y")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n\n p = Period(freq="Y", year=2007)\n for freq in ["2M", offsets.MonthEnd(2)]:\n result = p.asfreq(freq)\n expected = Period("2007-12", freq="2M")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n for freq in ["2M", offsets.MonthEnd(2)]:\n result = p.asfreq(freq, how="s")\n expected = Period("2007-01", freq="2M")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n\n p = Period(freq="3Y", year=2007)\n for freq in ["2M", offsets.MonthEnd(2)]:\n result = p.asfreq(freq)\n expected = Period("2009-12", freq="2M")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n for freq in ["2M", offsets.MonthEnd(2)]:\n result = p.asfreq(freq, how="s")\n expected = Period("2007-01", freq="2M")\n\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n\n def test_asfreq_combined(self):\n # normal freq to combined freq\n p = Period("2007", freq="h")\n\n # ordinal will not change\n expected = Period("2007", freq="25h")\n for freq, how in zip(["1D1h", "1h1D"], ["E", "S"]):\n result = p.asfreq(freq, how=how)\n assert result == expected\n assert result.ordinal == expected.ordinal\n assert result.freq == expected.freq\n\n # combined freq to normal freq\n p1 = Period(freq="1D1h", year=2007)\n p2 = Period(freq="1h1D", year=2007)\n\n # ordinal will change because how=E is the default\n result1 = p1.asfreq("h")\n result2 = p2.asfreq("h")\n expected = Period("2007-01-02", freq="h")\n assert result1 == expected\n assert result1.ordinal == expected.ordinal\n assert result1.freq == expected.freq\n assert result2 == expected\n assert result2.ordinal == expected.ordinal\n assert result2.freq == expected.freq\n\n # ordinal will not change\n result1 = p1.asfreq("h", how="S")\n result2 = p2.asfreq("h", how="S")\n expected = Period("2007-01-01", freq="h")\n assert result1 == expected\n assert result1.ordinal == expected.ordinal\n assert result1.freq == expected.freq\n assert result2 == expected\n assert result2.ordinal == expected.ordinal\n assert result2.freq == expected.freq\n\n def test_asfreq_MS(self):\n initial = Period("2013")\n\n assert initial.asfreq(freq="M", how="S") == Period("2013-01", "M")\n\n msg = "MS is not supported as period frequency"\n with pytest.raises(ValueError, match=msg):\n initial.asfreq(freq="MS", how="S")\n\n with pytest.raises(ValueError, match=msg):\n Period("2013-01", "MS")\n
.venv\Lib\site-packages\pandas\tests\scalar\period\test_asfreq.py
test_asfreq.py
Python
38,445
0.95
0.03744
0.036671
python-kit
227
2023-08-14T13:37:13.449903
BSD-3-Clause
true
f7c94c5b3530622aca8f9edbdcb11d19
from datetime import (\n date,\n datetime,\n timedelta,\n)\nimport re\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import iNaT\nfrom pandas._libs.tslibs.ccalendar import (\n DAYS,\n MONTHS,\n)\nfrom pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime\nfrom pandas._libs.tslibs.parsing import DateParseError\nfrom pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\n\nfrom pandas import (\n NaT,\n Period,\n Timedelta,\n Timestamp,\n offsets,\n)\nimport pandas._testing as tm\n\nbday_msg = "Period with BDay freq is deprecated"\n\n\nclass TestPeriodDisallowedFreqs:\n @pytest.mark.parametrize(\n "freq, freq_msg",\n [\n (offsets.BYearBegin(), "BYearBegin"),\n (offsets.YearBegin(2), "YearBegin"),\n (offsets.QuarterBegin(startingMonth=12), "QuarterBegin"),\n (offsets.BusinessMonthEnd(2), "BusinessMonthEnd"),\n ],\n )\n def test_offsets_not_supported(self, freq, freq_msg):\n # GH#55785\n msg = re.escape(f"{freq} is not supported as period frequency")\n with pytest.raises(ValueError, match=msg):\n Period(year=2014, freq=freq)\n\n def test_custom_business_day_freq_raises(self):\n # GH#52534\n msg = "C is not supported as period frequency"\n with pytest.raises(ValueError, match=msg):\n Period("2023-04-10", freq="C")\n msg = f"{offsets.CustomBusinessDay().base} is not supported as period frequency"\n with pytest.raises(ValueError, match=msg):\n Period("2023-04-10", freq=offsets.CustomBusinessDay())\n\n def test_invalid_frequency_error_message(self):\n msg = "WOM-1MON is not supported as period frequency"\n with pytest.raises(ValueError, match=msg):\n Period("2012-01-02", freq="WOM-1MON")\n\n def test_invalid_frequency_period_error_message(self):\n msg = "for Period, please use 'M' instead of 'ME'"\n with pytest.raises(ValueError, match=msg):\n Period("2012-01-02", freq="ME")\n\n\nclass TestPeriodConstruction:\n def test_from_td64nat_raises(self):\n # GH#44507\n td = NaT.to_numpy("m8[ns]")\n\n msg = "Value must be Period, string, integer, or datetime"\n with pytest.raises(ValueError, match=msg):\n Period(td)\n\n with pytest.raises(ValueError, match=msg):\n Period(td, freq="D")\n\n def test_construction(self):\n i1 = Period("1/1/2005", freq="M")\n i2 = Period("Jan 2005")\n\n assert i1 == i2\n\n # GH#54105 - Period can be confusingly instantiated with lowercase freq\n # TODO: raise in the future an error when passing lowercase freq\n i1 = Period("2005", freq="Y")\n i2 = Period("2005")\n\n assert i1 == i2\n\n i4 = Period("2005", freq="M")\n assert i1 != i4\n\n i1 = Period.now(freq="Q")\n i2 = Period(datetime.now(), freq="Q")\n\n assert i1 == i2\n\n # Pass in freq as a keyword argument sometimes as a test for\n # https://github.com/pandas-dev/pandas/issues/53369\n i1 = Period.now(freq="D")\n i2 = Period(datetime.now(), freq="D")\n i3 = Period.now(offsets.Day())\n\n assert i1 == i2\n assert i1 == i3\n\n i1 = Period("1982", freq="min")\n msg = "'MIN' is deprecated and will be removed in a future version."\n with tm.assert_produces_warning(FutureWarning, match=msg):\n i2 = Period("1982", freq="MIN")\n assert i1 == i2\n\n i1 = Period(year=2005, month=3, day=1, freq="D")\n i2 = Period("3/1/2005", freq="D")\n assert i1 == i2\n\n i3 = Period(year=2005, month=3, day=1, freq="d")\n assert i1 == i3\n\n i1 = Period("2007-01-01 09:00:00.001")\n expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")\n assert i1 == expected\n\n expected = Period("2007-01-01 09:00:00.001", freq="ms")\n assert i1 == expected\n\n i1 = Period("2007-01-01 09:00:00.00101")\n expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")\n assert i1 == expected\n\n expected = Period("2007-01-01 09:00:00.00101", freq="us")\n assert i1 == expected\n\n msg = "Must supply freq for ordinal value"\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=200701)\n\n msg = "Invalid frequency: X"\n with pytest.raises(ValueError, match=msg):\n Period("2007-1-1", freq="X")\n\n def test_tuple_freq_disallowed(self):\n # GH#34703 tuple freq disallowed\n with pytest.raises(TypeError, match="pass as a string instead"):\n Period("1982", freq=("Min", 1))\n\n with pytest.raises(TypeError, match="pass as a string instead"):\n Period("2006-12-31", ("w", 1))\n\n def test_construction_from_timestamp_nanos(self):\n # GH#46811 don't drop nanos from Timestamp\n ts = Timestamp("2022-04-20 09:23:24.123456789")\n per = Period(ts, freq="ns")\n\n # should losslessly round-trip, not lose the 789\n rt = per.to_timestamp()\n assert rt == ts\n\n # same thing but from a datetime64 object\n dt64 = ts.asm8\n per2 = Period(dt64, freq="ns")\n rt2 = per2.to_timestamp()\n assert rt2.asm8 == dt64\n\n def test_construction_bday(self):\n # Biz day construction, roll forward if non-weekday\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n i1 = Period("3/10/12", freq="B")\n i2 = Period("3/10/12", freq="D")\n assert i1 == i2.asfreq("B")\n i2 = Period("3/11/12", freq="D")\n assert i1 == i2.asfreq("B")\n i2 = Period("3/12/12", freq="D")\n assert i1 == i2.asfreq("B")\n\n i3 = Period("3/10/12", freq="b")\n assert i1 == i3\n\n i1 = Period(year=2012, month=3, day=10, freq="B")\n i2 = Period("3/12/12", freq="B")\n assert i1 == i2\n\n def test_construction_quarter(self):\n i1 = Period(year=2005, quarter=1, freq="Q")\n i2 = Period("1/1/2005", freq="Q")\n assert i1 == i2\n\n i1 = Period(year=2005, quarter=3, freq="Q")\n i2 = Period("9/1/2005", freq="Q")\n assert i1 == i2\n\n i1 = Period("2005Q1")\n i2 = Period(year=2005, quarter=1, freq="Q")\n i3 = Period("2005q1")\n assert i1 == i2\n assert i1 == i3\n\n i1 = Period("05Q1")\n assert i1 == i2\n lower = Period("05q1")\n assert i1 == lower\n\n i1 = Period("1Q2005")\n assert i1 == i2\n lower = Period("1q2005")\n assert i1 == lower\n\n i1 = Period("1Q05")\n assert i1 == i2\n lower = Period("1q05")\n assert i1 == lower\n\n i1 = Period("4Q1984")\n assert i1.year == 1984\n lower = Period("4q1984")\n assert i1 == lower\n\n def test_construction_month(self):\n expected = Period("2007-01", freq="M")\n i1 = Period("200701", freq="M")\n assert i1 == expected\n\n i1 = Period("200701", freq="M")\n assert i1 == expected\n\n i1 = Period(200701, freq="M")\n assert i1 == expected\n\n i1 = Period(ordinal=200701, freq="M")\n assert i1.year == 18695\n\n i1 = Period(datetime(2007, 1, 1), freq="M")\n i2 = Period("200701", freq="M")\n assert i1 == i2\n\n i1 = Period(date(2007, 1, 1), freq="M")\n i2 = Period(datetime(2007, 1, 1), freq="M")\n i3 = Period(np.datetime64("2007-01-01"), freq="M")\n i4 = Period("2007-01-01 00:00:00", freq="M")\n i5 = Period("2007-01-01 00:00:00.000", freq="M")\n assert i1 == i2\n assert i1 == i3\n assert i1 == i4\n assert i1 == i5\n\n def test_period_constructor_offsets(self):\n assert Period("1/1/2005", freq=offsets.MonthEnd()) == Period(\n "1/1/2005", freq="M"\n )\n assert Period("2005", freq=offsets.YearEnd()) == Period("2005", freq="Y")\n assert Period("2005", freq=offsets.MonthEnd()) == Period("2005", freq="M")\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert Period("3/10/12", freq=offsets.BusinessDay()) == Period(\n "3/10/12", freq="B"\n )\n assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D")\n\n assert Period(\n year=2005, quarter=1, freq=offsets.QuarterEnd(startingMonth=12)\n ) == Period(year=2005, quarter=1, freq="Q")\n assert Period(\n year=2005, quarter=2, freq=offsets.QuarterEnd(startingMonth=12)\n ) == Period(year=2005, quarter=2, freq="Q")\n\n assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period(\n year=2005, month=3, day=1, freq="D"\n )\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period(\n year=2012, month=3, day=10, freq="B"\n )\n\n expected = Period("2005-03-01", freq="3D")\n assert Period(year=2005, month=3, day=1, freq=offsets.Day(3)) == expected\n assert Period(year=2005, month=3, day=1, freq="3D") == expected\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period(\n year=2012, month=3, day=10, freq="3B"\n )\n\n assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M")\n\n i1 = Period(ordinal=200701, freq=offsets.MonthEnd())\n i2 = Period(ordinal=200701, freq="M")\n assert i1 == i2\n assert i1.year == 18695\n assert i2.year == 18695\n\n i1 = Period(datetime(2007, 1, 1), freq="M")\n i2 = Period("200701", freq="M")\n assert i1 == i2\n\n i1 = Period(date(2007, 1, 1), freq="M")\n i2 = Period(datetime(2007, 1, 1), freq="M")\n i3 = Period(np.datetime64("2007-01-01"), freq="M")\n i4 = Period("2007-01-01 00:00:00", freq="M")\n i5 = Period("2007-01-01 00:00:00.000", freq="M")\n assert i1 == i2\n assert i1 == i3\n assert i1 == i4\n assert i1 == i5\n\n i1 = Period("2007-01-01 09:00:00.001")\n expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")\n assert i1 == expected\n\n expected = Period("2007-01-01 09:00:00.001", freq="ms")\n assert i1 == expected\n\n i1 = Period("2007-01-01 09:00:00.00101")\n expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")\n assert i1 == expected\n\n expected = Period("2007-01-01 09:00:00.00101", freq="us")\n assert i1 == expected\n\n def test_invalid_arguments(self):\n msg = "Must supply freq for datetime value"\n with pytest.raises(ValueError, match=msg):\n Period(datetime.now())\n with pytest.raises(ValueError, match=msg):\n Period(datetime.now().date())\n\n msg = "Value must be Period, string, integer, or datetime"\n with pytest.raises(ValueError, match=msg):\n Period(1.6, freq="D")\n msg = "Ordinal must be an integer"\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=1.6, freq="D")\n msg = "Only value or ordinal but not both should be given but not both"\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=2, value=1, freq="D")\n\n msg = "If value is None, freq cannot be None"\n with pytest.raises(ValueError, match=msg):\n Period(month=1)\n\n msg = '^Given date string "-2000" not likely a datetime$'\n with pytest.raises(ValueError, match=msg):\n Period("-2000", "Y")\n msg = "day is out of range for month"\n with pytest.raises(DateParseError, match=msg):\n Period("0", "Y")\n msg = "Unknown datetime string format, unable to parse"\n with pytest.raises(DateParseError, match=msg):\n Period("1/1/-2000", "Y")\n\n def test_constructor_corner(self):\n expected = Period("2007-01", freq="2M")\n assert Period(year=2007, month=1, freq="2M") == expected\n\n assert Period(None) is NaT\n\n p = Period("2007-01-01", freq="D")\n\n result = Period(p, freq="Y")\n exp = Period("2007", freq="Y")\n assert result == exp\n\n def test_constructor_infer_freq(self):\n p = Period("2007-01-01")\n assert p.freq == "D"\n\n p = Period("2007-01-01 07")\n assert p.freq == "h"\n\n p = Period("2007-01-01 07:10")\n assert p.freq == "min"\n\n p = Period("2007-01-01 07:10:15")\n assert p.freq == "s"\n\n p = Period("2007-01-01 07:10:15.123")\n assert p.freq == "ms"\n\n # We see that there are 6 digits after the decimal, so get microsecond\n # even though they are all zeros.\n p = Period("2007-01-01 07:10:15.123000")\n assert p.freq == "us"\n\n p = Period("2007-01-01 07:10:15.123400")\n assert p.freq == "us"\n\n def test_multiples(self):\n result1 = Period("1989", freq="2Y")\n result2 = Period("1989", freq="Y")\n assert result1.ordinal == result2.ordinal\n assert result1.freqstr == "2Y-DEC"\n assert result2.freqstr == "Y-DEC"\n assert result1.freq == offsets.YearEnd(2)\n assert result2.freq == offsets.YearEnd()\n\n assert (result1 + 1).ordinal == result1.ordinal + 2\n assert (1 + result1).ordinal == result1.ordinal + 2\n assert (result1 - 1).ordinal == result2.ordinal - 2\n assert (-1 + result1).ordinal == result2.ordinal - 2\n\n @pytest.mark.parametrize("month", MONTHS)\n def test_period_cons_quarterly(self, month):\n # bugs in scikits.timeseries\n freq = f"Q-{month}"\n exp = Period("1989Q3", freq=freq)\n assert "1989Q3" in str(exp)\n stamp = exp.to_timestamp("D", how="end")\n p = Period(stamp, freq=freq)\n assert p == exp\n\n stamp = exp.to_timestamp("3D", how="end")\n p = Period(stamp, freq=freq)\n assert p == exp\n\n @pytest.mark.parametrize("month", MONTHS)\n def test_period_cons_annual(self, month):\n # bugs in scikits.timeseries\n freq = f"Y-{month}"\n exp = Period("1989", freq=freq)\n stamp = exp.to_timestamp("D", how="end") + timedelta(days=30)\n p = Period(stamp, freq=freq)\n\n assert p == exp + 1\n assert isinstance(p, Period)\n\n @pytest.mark.parametrize("day", DAYS)\n @pytest.mark.parametrize("num", range(10, 17))\n def test_period_cons_weekly(self, num, day):\n daystr = f"2011-02-{num}"\n freq = f"W-{day}"\n\n result = Period(daystr, freq=freq)\n expected = Period(daystr, freq="D").asfreq(freq)\n assert result == expected\n assert isinstance(result, Period)\n\n def test_parse_week_str_roundstrip(self):\n # GH#50803\n per = Period("2017-01-23/2017-01-29")\n assert per.freq.freqstr == "W-SUN"\n\n per = Period("2017-01-24/2017-01-30")\n assert per.freq.freqstr == "W-MON"\n\n msg = "Could not parse as weekly-freq Period"\n with pytest.raises(ValueError, match=msg):\n # not 6 days apart\n Period("2016-01-23/2017-01-29")\n\n def test_period_from_ordinal(self):\n p = Period("2011-01", freq="M")\n res = Period._from_ordinal(p.ordinal, freq=p.freq)\n assert p == res\n assert isinstance(res, Period)\n\n @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])\n def test_construct_from_nat_string_and_freq(self, freq):\n per = Period("NaT", freq=freq)\n assert per is NaT\n\n per = Period("NaT", freq="2" + freq)\n assert per is NaT\n\n per = Period("NaT", freq="3" + freq)\n assert per is NaT\n\n def test_period_cons_nat(self):\n p = Period("nat", freq="W-SUN")\n assert p is NaT\n\n p = Period(iNaT, freq="D")\n assert p is NaT\n\n p = Period(iNaT, freq="3D")\n assert p is NaT\n\n p = Period(iNaT, freq="1D1h")\n assert p is NaT\n\n p = Period("NaT")\n assert p is NaT\n\n p = Period(iNaT)\n assert p is NaT\n\n def test_period_cons_mult(self):\n p1 = Period("2011-01", freq="3M")\n p2 = Period("2011-01", freq="M")\n assert p1.ordinal == p2.ordinal\n\n assert p1.freq == offsets.MonthEnd(3)\n assert p1.freqstr == "3M"\n\n assert p2.freq == offsets.MonthEnd()\n assert p2.freqstr == "M"\n\n result = p1 + 1\n assert result.ordinal == (p2 + 3).ordinal\n\n assert result.freq == p1.freq\n assert result.freqstr == "3M"\n\n result = p1 - 1\n assert result.ordinal == (p2 - 3).ordinal\n assert result.freq == p1.freq\n assert result.freqstr == "3M"\n\n msg = "Frequency must be positive, because it represents span: -3M"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="-3M")\n\n msg = "Frequency must be positive, because it represents span: 0M"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="0M")\n\n def test_period_cons_combined(self):\n p = [\n (\n Period("2011-01", freq="1D1h"),\n Period("2011-01", freq="1h1D"),\n Period("2011-01", freq="h"),\n ),\n (\n Period(ordinal=1, freq="1D1h"),\n Period(ordinal=1, freq="1h1D"),\n Period(ordinal=1, freq="h"),\n ),\n ]\n\n for p1, p2, p3 in p:\n assert p1.ordinal == p3.ordinal\n assert p2.ordinal == p3.ordinal\n\n assert p1.freq == offsets.Hour(25)\n assert p1.freqstr == "25h"\n\n assert p2.freq == offsets.Hour(25)\n assert p2.freqstr == "25h"\n\n assert p3.freq == offsets.Hour()\n assert p3.freqstr == "h"\n\n result = p1 + 1\n assert result.ordinal == (p3 + 25).ordinal\n assert result.freq == p1.freq\n assert result.freqstr == "25h"\n\n result = p2 + 1\n assert result.ordinal == (p3 + 25).ordinal\n assert result.freq == p2.freq\n assert result.freqstr == "25h"\n\n result = p1 - 1\n assert result.ordinal == (p3 - 25).ordinal\n assert result.freq == p1.freq\n assert result.freqstr == "25h"\n\n result = p2 - 1\n assert result.ordinal == (p3 - 25).ordinal\n assert result.freq == p2.freq\n assert result.freqstr == "25h"\n\n msg = "Frequency must be positive, because it represents span: -25h"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="-1D1h")\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="-1h1D")\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=1, freq="-1D1h")\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=1, freq="-1h1D")\n\n msg = "Frequency must be positive, because it represents span: 0D"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="0D0h")\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=1, freq="0D0h")\n\n # You can only combine together day and intraday offsets\n msg = "Invalid frequency: 1W1D"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="1W1D")\n msg = "Invalid frequency: 1D1W"\n with pytest.raises(ValueError, match=msg):\n Period("2011-01", freq="1D1W")\n\n @pytest.mark.parametrize("day", ["1970/01/01 ", "2020-12-31 ", "1981/09/13 "])\n @pytest.mark.parametrize("hour", ["00:00:00", "00:00:01", "23:59:59", "12:00:59"])\n @pytest.mark.parametrize(\n "sec_float, expected",\n [\n (".000000001", 1),\n (".000000999", 999),\n (".123456789", 789),\n (".999999999", 999),\n (".999999000", 0),\n # Test femtoseconds, attoseconds, picoseconds are dropped like Timestamp\n (".999999001123", 1),\n (".999999001123456", 1),\n (".999999001123456789", 1),\n ],\n )\n def test_period_constructor_nanosecond(self, day, hour, sec_float, expected):\n # GH 34621\n\n assert Period(day + hour + sec_float).start_time.nanosecond == expected\n\n @pytest.mark.parametrize("hour", range(24))\n def test_period_large_ordinal(self, hour):\n # Issue #36430\n # Integer overflow for Period over the maximum timestamp\n p = Period(ordinal=2562048 + hour, freq="1h")\n assert p.hour == hour\n\n\nclass TestPeriodMethods:\n def test_round_trip(self):\n p = Period("2000Q1")\n new_p = tm.round_trip_pickle(p)\n assert new_p == p\n\n def test_hash(self):\n assert hash(Period("2011-01", freq="M")) == hash(Period("2011-01", freq="M"))\n\n assert hash(Period("2011-01-01", freq="D")) != hash(Period("2011-01", freq="M"))\n\n assert hash(Period("2011-01", freq="3M")) != hash(Period("2011-01", freq="2M"))\n\n assert hash(Period("2011-01", freq="M")) != hash(Period("2011-02", freq="M"))\n\n # --------------------------------------------------------------\n # to_timestamp\n\n def test_to_timestamp_mult(self):\n p = Period("2011-01", freq="M")\n assert p.to_timestamp(how="S") == Timestamp("2011-01-01")\n expected = Timestamp("2011-02-01") - Timedelta(1, "ns")\n assert p.to_timestamp(how="E") == expected\n\n p = Period("2011-01", freq="3M")\n assert p.to_timestamp(how="S") == Timestamp("2011-01-01")\n expected = Timestamp("2011-04-01") - Timedelta(1, "ns")\n assert p.to_timestamp(how="E") == expected\n\n @pytest.mark.filterwarnings(\n "ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n def test_to_timestamp(self):\n p = Period("1982", freq="Y")\n start_ts = p.to_timestamp(how="S")\n aliases = ["s", "StarT", "BEGIn"]\n for a in aliases:\n assert start_ts == p.to_timestamp("D", how=a)\n # freq with mult should not affect to the result\n assert start_ts == p.to_timestamp("3D", how=a)\n\n end_ts = p.to_timestamp(how="E")\n aliases = ["e", "end", "FINIsH"]\n for a in aliases:\n assert end_ts == p.to_timestamp("D", how=a)\n assert end_ts == p.to_timestamp("3D", how=a)\n\n from_lst = ["Y", "Q", "M", "W", "B", "D", "h", "Min", "s"]\n\n def _ex(p):\n if p.freq == "B":\n return p.start_time + Timedelta(days=1, nanoseconds=-1)\n return Timestamp((p + p.freq).start_time._value - 1)\n\n for fcode in from_lst:\n p = Period("1982", freq=fcode)\n result = p.to_timestamp().to_period(fcode)\n assert result == p\n\n assert p.start_time == p.to_timestamp(how="S")\n\n assert p.end_time == _ex(p)\n\n # Frequency other than daily\n\n p = Period("1985", freq="Y")\n\n result = p.to_timestamp("h", how="end")\n expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")\n assert result == expected\n result = p.to_timestamp("3h", how="end")\n assert result == expected\n\n result = p.to_timestamp("min", how="end")\n expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")\n assert result == expected\n result = p.to_timestamp("2min", how="end")\n assert result == expected\n\n result = p.to_timestamp(how="end")\n expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")\n assert result == expected\n\n expected = datetime(1985, 1, 1)\n result = p.to_timestamp("h", how="start")\n assert result == expected\n result = p.to_timestamp("min", how="start")\n assert result == expected\n result = p.to_timestamp("s", how="start")\n assert result == expected\n result = p.to_timestamp("3h", how="start")\n assert result == expected\n result = p.to_timestamp("5s", how="start")\n assert result == expected\n\n def test_to_timestamp_business_end(self):\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per = Period("1990-01-05", "B") # Friday\n result = per.to_timestamp("B", how="E")\n\n expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)\n assert result == expected\n\n @pytest.mark.parametrize(\n "ts, expected",\n [\n ("1970-01-01 00:00:00", 0),\n ("1970-01-01 00:00:00.000001", 1),\n ("1970-01-01 00:00:00.00001", 10),\n ("1970-01-01 00:00:00.499", 499000),\n ("1999-12-31 23:59:59.999", 999000),\n ("1999-12-31 23:59:59.999999", 999999),\n ("2050-12-31 23:59:59.5", 500000),\n ("2050-12-31 23:59:59.500001", 500001),\n ("2050-12-31 23:59:59.123456", 123456),\n ],\n )\n @pytest.mark.parametrize("freq", [None, "us", "ns"])\n def test_to_timestamp_microsecond(self, ts, expected, freq):\n # GH 24444\n result = Period(ts).to_timestamp(freq=freq).microsecond\n assert result == expected\n\n # --------------------------------------------------------------\n # Rendering: __repr__, strftime, etc\n\n @pytest.mark.parametrize(\n "str_ts,freq,str_res,str_freq",\n (\n ("Jan-2000", None, "2000-01", "M"),\n ("2000-12-15", None, "2000-12-15", "D"),\n (\n "2000-12-15 13:45:26.123456789",\n "ns",\n "2000-12-15 13:45:26.123456789",\n "ns",\n ),\n ("2000-12-15 13:45:26.123456789", "us", "2000-12-15 13:45:26.123456", "us"),\n ("2000-12-15 13:45:26.123456", None, "2000-12-15 13:45:26.123456", "us"),\n ("2000-12-15 13:45:26.123456789", "ms", "2000-12-15 13:45:26.123", "ms"),\n ("2000-12-15 13:45:26.123", None, "2000-12-15 13:45:26.123", "ms"),\n ("2000-12-15 13:45:26", "s", "2000-12-15 13:45:26", "s"),\n ("2000-12-15 13:45:26", "min", "2000-12-15 13:45", "min"),\n ("2000-12-15 13:45:26", "h", "2000-12-15 13:00", "h"),\n ("2000-12-15", "Y", "2000", "Y-DEC"),\n ("2000-12-15", "Q", "2000Q4", "Q-DEC"),\n ("2000-12-15", "M", "2000-12", "M"),\n ("2000-12-15", "W", "2000-12-11/2000-12-17", "W-SUN"),\n ("2000-12-15", "D", "2000-12-15", "D"),\n ("2000-12-15", "B", "2000-12-15", "B"),\n ),\n )\n @pytest.mark.filterwarnings(\n "ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n def test_repr(self, str_ts, freq, str_res, str_freq):\n p = Period(str_ts, freq=freq)\n assert str(p) == str_res\n assert repr(p) == f"Period('{str_res}', '{str_freq}')"\n\n def test_repr_nat(self):\n p = Period("nat", freq="M")\n assert repr(NaT) in repr(p)\n\n def test_strftime(self):\n # GH#3363\n p = Period("2000-1-1 12:34:12", freq="s")\n res = p.strftime("%Y-%m-%d %H:%M:%S")\n assert res == "2000-01-01 12:34:12"\n assert isinstance(res, str)\n\n\nclass TestPeriodProperties:\n """Test properties such as year, month, weekday, etc...."""\n\n @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])\n def test_is_leap_year(self, freq):\n # GH 13727\n p = Period("2000-01-01 00:00:00", freq=freq)\n assert p.is_leap_year\n assert isinstance(p.is_leap_year, bool)\n\n p = Period("1999-01-01 00:00:00", freq=freq)\n assert not p.is_leap_year\n\n p = Period("2004-01-01 00:00:00", freq=freq)\n assert p.is_leap_year\n\n p = Period("2100-01-01 00:00:00", freq=freq)\n assert not p.is_leap_year\n\n def test_quarterly_negative_ordinals(self):\n p = Period(ordinal=-1, freq="Q-DEC")\n assert p.year == 1969\n assert p.quarter == 4\n assert isinstance(p, Period)\n\n p = Period(ordinal=-2, freq="Q-DEC")\n assert p.year == 1969\n assert p.quarter == 3\n assert isinstance(p, Period)\n\n p = Period(ordinal=-2, freq="M")\n assert p.year == 1969\n assert p.month == 11\n assert isinstance(p, Period)\n\n def test_freq_str(self):\n i1 = Period("1982", freq="Min")\n assert i1.freq == offsets.Minute()\n assert i1.freqstr == "min"\n\n @pytest.mark.filterwarnings(\n "ignore:Period with BDay freq is deprecated:FutureWarning"\n )\n def test_period_deprecated_freq(self):\n cases = {\n "M": ["MTH", "MONTH", "MONTHLY", "Mth", "month", "monthly"],\n "B": ["BUS", "BUSINESS", "BUSINESSLY", "WEEKDAY", "bus"],\n "D": ["DAY", "DLY", "DAILY", "Day", "Dly", "Daily"],\n "h": ["HR", "HOUR", "HRLY", "HOURLY", "hr", "Hour", "HRly"],\n "min": ["minute", "MINUTE", "MINUTELY", "minutely"],\n "s": ["sec", "SEC", "SECOND", "SECONDLY", "second"],\n "ms": ["MILLISECOND", "MILLISECONDLY", "millisecond"],\n "us": ["MICROSECOND", "MICROSECONDLY", "microsecond"],\n "ns": ["NANOSECOND", "NANOSECONDLY", "nanosecond"],\n }\n\n msg = INVALID_FREQ_ERR_MSG\n for exp, freqs in cases.items():\n for freq in freqs:\n with pytest.raises(ValueError, match=msg):\n Period("2016-03-01 09:00", freq=freq)\n with pytest.raises(ValueError, match=msg):\n Period(ordinal=1, freq=freq)\n\n # check supported freq-aliases still works\n p1 = Period("2016-03-01 09:00", freq=exp)\n p2 = Period(ordinal=1, freq=exp)\n assert isinstance(p1, Period)\n assert isinstance(p2, Period)\n\n @staticmethod\n def _period_constructor(bound, offset):\n return Period(\n year=bound.year,\n month=bound.month,\n day=bound.day,\n hour=bound.hour,\n minute=bound.minute,\n second=bound.second + offset,\n freq="us",\n )\n\n @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])\n @pytest.mark.parametrize("period_property", ["start_time", "end_time"])\n def test_outer_bounds_start_and_end_time(self, bound, offset, period_property):\n # GH #13346\n period = TestPeriodProperties._period_constructor(bound, offset)\n with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond"):\n getattr(period, period_property)\n\n @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])\n @pytest.mark.parametrize("period_property", ["start_time", "end_time"])\n def test_inner_bounds_start_and_end_time(self, bound, offset, period_property):\n # GH #13346\n period = TestPeriodProperties._period_constructor(bound, -offset)\n expected = period.to_timestamp().round(freq="s")\n assert getattr(period, period_property).round(freq="s") == expected\n expected = (bound - offset * Timedelta(1, unit="s")).floor("s")\n assert getattr(period, period_property).floor("s") == expected\n\n def test_start_time(self):\n freq_lst = ["Y", "Q", "M", "D", "h", "min", "s"]\n xp = datetime(2012, 1, 1)\n for f in freq_lst:\n p = Period("2012", freq=f)\n assert p.start_time == xp\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert Period("2012", freq="B").start_time == datetime(2012, 1, 2)\n assert Period("2012", freq="W").start_time == datetime(2011, 12, 26)\n\n def test_end_time(self):\n p = Period("2012", freq="Y")\n\n def _ex(*args):\n return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)\n\n xp = _ex(2013, 1, 1)\n assert xp == p.end_time\n\n p = Period("2012", freq="Q")\n xp = _ex(2012, 4, 1)\n assert xp == p.end_time\n\n p = Period("2012", freq="M")\n xp = _ex(2012, 2, 1)\n assert xp == p.end_time\n\n p = Period("2012", freq="D")\n xp = _ex(2012, 1, 2)\n assert xp == p.end_time\n\n p = Period("2012", freq="h")\n xp = _ex(2012, 1, 1, 1)\n assert xp == p.end_time\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n p = Period("2012", freq="B")\n xp = _ex(2012, 1, 3)\n assert xp == p.end_time\n\n p = Period("2012", freq="W")\n xp = _ex(2012, 1, 2)\n assert xp == p.end_time\n\n # Test for GH 11738\n p = Period("2012", freq="15D")\n xp = _ex(2012, 1, 16)\n assert xp == p.end_time\n\n p = Period("2012", freq="1D1h")\n xp = _ex(2012, 1, 2, 1)\n assert xp == p.end_time\n\n p = Period("2012", freq="1h1D")\n xp = _ex(2012, 1, 2, 1)\n assert xp == p.end_time\n\n def test_end_time_business_friday(self):\n # GH#34449\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per = Period("1990-01-05", "B")\n result = per.end_time\n\n expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)\n assert result == expected\n\n def test_anchor_week_end_time(self):\n def _ex(*args):\n return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)\n\n p = Period("2013-1-1", "W-SAT")\n xp = _ex(2013, 1, 6)\n assert p.end_time == xp\n\n def test_properties_annually(self):\n # Test properties on Periods with annually frequency.\n a_date = Period(freq="Y", year=2007)\n assert a_date.year == 2007\n\n def test_properties_quarterly(self):\n # Test properties on Periods with daily frequency.\n qedec_date = Period(freq="Q-DEC", year=2007, quarter=1)\n qejan_date = Period(freq="Q-JAN", year=2007, quarter=1)\n qejun_date = Period(freq="Q-JUN", year=2007, quarter=1)\n #\n for x in range(3):\n for qd in (qedec_date, qejan_date, qejun_date):\n assert (qd + x).qyear == 2007\n assert (qd + x).quarter == x + 1\n\n def test_properties_monthly(self):\n # Test properties on Periods with daily frequency.\n m_date = Period(freq="M", year=2007, month=1)\n for x in range(11):\n m_ival_x = m_date + x\n assert m_ival_x.year == 2007\n if 1 <= x + 1 <= 3:\n assert m_ival_x.quarter == 1\n elif 4 <= x + 1 <= 6:\n assert m_ival_x.quarter == 2\n elif 7 <= x + 1 <= 9:\n assert m_ival_x.quarter == 3\n elif 10 <= x + 1 <= 12:\n assert m_ival_x.quarter == 4\n assert m_ival_x.month == x + 1\n\n def test_properties_weekly(self):\n # Test properties on Periods with daily frequency.\n w_date = Period(freq="W", year=2007, month=1, day=7)\n #\n assert w_date.year == 2007\n assert w_date.quarter == 1\n assert w_date.month == 1\n assert w_date.week == 1\n assert (w_date - 1).week == 52\n assert w_date.days_in_month == 31\n assert Period(freq="W", year=2012, month=2, day=1).days_in_month == 29\n\n def test_properties_weekly_legacy(self):\n # Test properties on Periods with daily frequency.\n w_date = Period(freq="W", year=2007, month=1, day=7)\n assert w_date.year == 2007\n assert w_date.quarter == 1\n assert w_date.month == 1\n assert w_date.week == 1\n assert (w_date - 1).week == 52\n assert w_date.days_in_month == 31\n\n exp = Period(freq="W", year=2012, month=2, day=1)\n assert exp.days_in_month == 29\n\n msg = INVALID_FREQ_ERR_MSG\n with pytest.raises(ValueError, match=msg):\n Period(freq="WK", year=2007, month=1, day=7)\n\n def test_properties_daily(self):\n # Test properties on Periods with daily frequency.\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n b_date = Period(freq="B", year=2007, month=1, day=1)\n #\n assert b_date.year == 2007\n assert b_date.quarter == 1\n assert b_date.month == 1\n assert b_date.day == 1\n assert b_date.weekday == 0\n assert b_date.dayofyear == 1\n assert b_date.days_in_month == 31\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29\n\n d_date = Period(freq="D", year=2007, month=1, day=1)\n\n assert d_date.year == 2007\n assert d_date.quarter == 1\n assert d_date.month == 1\n assert d_date.day == 1\n assert d_date.weekday == 0\n assert d_date.dayofyear == 1\n assert d_date.days_in_month == 31\n assert Period(freq="D", year=2012, month=2, day=1).days_in_month == 29\n\n def test_properties_hourly(self):\n # Test properties on Periods with hourly frequency.\n h_date1 = Period(freq="h", year=2007, month=1, day=1, hour=0)\n h_date2 = Period(freq="2h", year=2007, month=1, day=1, hour=0)\n\n for h_date in [h_date1, h_date2]:\n assert h_date.year == 2007\n assert h_date.quarter == 1\n assert h_date.month == 1\n assert h_date.day == 1\n assert h_date.weekday == 0\n assert h_date.dayofyear == 1\n assert h_date.hour == 0\n assert h_date.days_in_month == 31\n assert (\n Period(freq="h", year=2012, month=2, day=1, hour=0).days_in_month == 29\n )\n\n def test_properties_minutely(self):\n # Test properties on Periods with minutely frequency.\n t_date = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0)\n #\n assert t_date.quarter == 1\n assert t_date.month == 1\n assert t_date.day == 1\n assert t_date.weekday == 0\n assert t_date.dayofyear == 1\n assert t_date.hour == 0\n assert t_date.minute == 0\n assert t_date.days_in_month == 31\n assert (\n Period(freq="D", year=2012, month=2, day=1, hour=0, minute=0).days_in_month\n == 29\n )\n\n def test_properties_secondly(self):\n # Test properties on Periods with secondly frequency.\n s_date = Period(\n freq="Min", year=2007, month=1, day=1, hour=0, minute=0, second=0\n )\n #\n assert s_date.year == 2007\n assert s_date.quarter == 1\n assert s_date.month == 1\n assert s_date.day == 1\n assert s_date.weekday == 0\n assert s_date.dayofyear == 1\n assert s_date.hour == 0\n assert s_date.minute == 0\n assert s_date.second == 0\n assert s_date.days_in_month == 31\n assert (\n Period(\n freq="Min", year=2012, month=2, day=1, hour=0, minute=0, second=0\n ).days_in_month\n == 29\n )\n\n\nclass TestPeriodComparisons:\n def test_sort_periods(self):\n jan = Period("2000-01", "M")\n feb = Period("2000-02", "M")\n mar = Period("2000-03", "M")\n periods = [mar, jan, feb]\n correctPeriods = [jan, feb, mar]\n assert sorted(periods) == correctPeriods\n\n\ndef test_period_immutable():\n # see gh-17116\n msg = "not writable"\n\n per = Period("2014Q1")\n with pytest.raises(AttributeError, match=msg):\n per.ordinal = 14\n\n freq = per.freq\n with pytest.raises(AttributeError, match=msg):\n per.freq = 2 * freq\n\n\ndef test_small_year_parsing():\n per1 = Period("0001-01-07", "D")\n assert per1.year == 1\n assert per1.day == 7\n\n\ndef test_negone_ordinals():\n freqs = ["Y", "M", "Q", "D", "h", "min", "s"]\n\n period = Period(ordinal=-1, freq="D")\n for freq in freqs:\n repr(period.asfreq(freq))\n\n for freq in freqs:\n period = Period(ordinal=-1, freq=freq)\n repr(period)\n assert period.year == 1969\n\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n period = Period(ordinal=-1, freq="B")\n repr(period)\n period = Period(ordinal=-1, freq="W")\n repr(period)\n
.venv\Lib\site-packages\pandas\tests\scalar\period\test_period.py
test_period.py
Python
40,121
0.95
0.078856
0.05526
vue-tools
392
2023-12-28T09:20:36.252352
MIT
true
8c4aba77234af341a90234ed0494a710
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\period\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
24,910
0.8
0.007968
0
vue-tools
643
2025-05-28T21:05:25.204593
Apache-2.0
true
a070edc278c4f1029496363e540c8c37
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\period\__pycache__\test_asfreq.cpython-313.pyc
test_asfreq.cpython-313.pyc
Other
44,993
0.8
0
0
awesome-app
66
2024-07-09T14:50:12.976306
Apache-2.0
true
640901a4b2caa91ac7b594aab8d3c32b
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\period\__pycache__\test_period.cpython-313.pyc
test_period.cpython-313.pyc
Other
59,971
0.6
0.005291
0.002695
vue-tools
159
2025-04-11T15:27:25.307209
Apache-2.0
true
791e24ddb35e536927e4890546c82ddb
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\period\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
201
0.7
0
0
vue-tools
43
2023-10-28T05:27:47.509979
MIT
true
68d8989166ac42c074475516020ed605
"""\nTests for scalar Timedelta arithmetic ops\n"""\nfrom datetime import (\n datetime,\n timedelta,\n)\nimport operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import OutOfBoundsTimedelta\n\nimport pandas as pd\nfrom pandas import (\n NaT,\n Timedelta,\n Timestamp,\n offsets,\n)\nimport pandas._testing as tm\nfrom pandas.core import ops\n\n\nclass TestTimedeltaAdditionSubtraction:\n """\n Tests for Timedelta methods:\n\n __add__, __radd__,\n __sub__, __rsub__\n """\n\n @pytest.mark.parametrize(\n "ten_seconds",\n [\n Timedelta(10, unit="s"),\n timedelta(seconds=10),\n np.timedelta64(10, "s"),\n np.timedelta64(10000000000, "ns"),\n offsets.Second(10),\n ],\n )\n def test_td_add_sub_ten_seconds(self, ten_seconds):\n # GH#6808\n base = Timestamp("20130101 09:01:12.123456")\n expected_add = Timestamp("20130101 09:01:22.123456")\n expected_sub = Timestamp("20130101 09:01:02.123456")\n\n result = base + ten_seconds\n assert result == expected_add\n\n result = base - ten_seconds\n assert result == expected_sub\n\n @pytest.mark.parametrize(\n "one_day_ten_secs",\n [\n Timedelta("1 day, 00:00:10"),\n Timedelta("1 days, 00:00:10"),\n timedelta(days=1, seconds=10),\n np.timedelta64(1, "D") + np.timedelta64(10, "s"),\n offsets.Day() + offsets.Second(10),\n ],\n )\n def test_td_add_sub_one_day_ten_seconds(self, one_day_ten_secs):\n # GH#6808\n base = Timestamp("20130102 09:01:12.123456")\n expected_add = Timestamp("20130103 09:01:22.123456")\n expected_sub = Timestamp("20130101 09:01:02.123456")\n\n result = base + one_day_ten_secs\n assert result == expected_add\n\n result = base - one_day_ten_secs\n assert result == expected_sub\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_datetimelike_scalar(self, op):\n # GH#19738\n td = Timedelta(10, unit="d")\n\n result = op(td, datetime(2016, 1, 1))\n if op is operator.add:\n # datetime + Timedelta does _not_ call Timedelta.__radd__,\n # so we get a datetime back instead of a Timestamp\n assert isinstance(result, Timestamp)\n assert result == Timestamp(2016, 1, 11)\n\n result = op(td, Timestamp("2018-01-12 18:09"))\n assert isinstance(result, Timestamp)\n assert result == Timestamp("2018-01-22 18:09")\n\n result = op(td, np.datetime64("2018-01-12"))\n assert isinstance(result, Timestamp)\n assert result == Timestamp("2018-01-22")\n\n result = op(td, NaT)\n assert result is NaT\n\n def test_td_add_timestamp_overflow(self):\n ts = Timestamp("1700-01-01").as_unit("ns")\n msg = "Cannot cast 259987 from D to 'ns' without overflow."\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n ts + Timedelta(13 * 19999, unit="D")\n\n msg = "Cannot cast 259987 days 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n ts + timedelta(days=13 * 19999)\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_td(self, op):\n td = Timedelta(10, unit="d")\n\n result = op(td, Timedelta(days=10))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=20)\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_pytimedelta(self, op):\n td = Timedelta(10, unit="d")\n result = op(td, timedelta(days=9))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=19)\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_timedelta64(self, op):\n td = Timedelta(10, unit="d")\n result = op(td, np.timedelta64(-4, "D"))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=6)\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_offset(self, op):\n td = Timedelta(10, unit="d")\n\n result = op(td, offsets.Hour(6))\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=10, hours=6)\n\n def test_td_sub_td(self):\n td = Timedelta(10, unit="d")\n expected = Timedelta(0, unit="ns")\n result = td - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_pytimedelta(self):\n td = Timedelta(10, unit="d")\n expected = Timedelta(0, unit="ns")\n\n result = td - td.to_pytimedelta()\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = td.to_pytimedelta() - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_timedelta64(self):\n td = Timedelta(10, unit="d")\n expected = Timedelta(0, unit="ns")\n\n result = td - td.to_timedelta64()\n assert isinstance(result, Timedelta)\n assert result == expected\n\n result = td.to_timedelta64() - td\n assert isinstance(result, Timedelta)\n assert result == expected\n\n def test_td_sub_nat(self):\n # In this context pd.NaT is treated as timedelta-like\n td = Timedelta(10, unit="d")\n result = td - NaT\n assert result is NaT\n\n def test_td_sub_td64_nat(self):\n td = Timedelta(10, unit="d")\n td_nat = np.timedelta64("NaT")\n\n result = td - td_nat\n assert result is NaT\n\n result = td_nat - td\n assert result is NaT\n\n def test_td_sub_offset(self):\n td = Timedelta(10, unit="d")\n result = td - offsets.Hour(1)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(239, unit="h")\n\n def test_td_add_sub_numeric_raises(self):\n td = Timedelta(10, unit="d")\n msg = "unsupported operand type"\n for other in [2, 2.0, np.int64(2), np.float64(2)]:\n with pytest.raises(TypeError, match=msg):\n td + other\n with pytest.raises(TypeError, match=msg):\n other + td\n with pytest.raises(TypeError, match=msg):\n td - other\n with pytest.raises(TypeError, match=msg):\n other - td\n\n def test_td_add_sub_int_ndarray(self):\n td = Timedelta("1 day")\n other = np.array([1])\n\n msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'"\n with pytest.raises(TypeError, match=msg):\n td + np.array([1])\n\n msg = "|".join(\n [\n (\n r"unsupported operand type\(s\) for \+: 'numpy.ndarray' "\n "and 'Timedelta'"\n ),\n # This message goes on to say "Please do not rely on this error;\n # it may not be given on all Python implementations"\n "Concatenation operation is not implemented for NumPy arrays",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n other + td\n msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'"\n with pytest.raises(TypeError, match=msg):\n td - other\n msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'"\n with pytest.raises(TypeError, match=msg):\n other - td\n\n def test_td_rsub_nat(self):\n td = Timedelta(10, unit="d")\n result = NaT - td\n assert result is NaT\n\n result = np.datetime64("NaT") - td\n assert result is NaT\n\n def test_td_rsub_offset(self):\n result = offsets.Hour(1) - Timedelta(10, unit="d")\n assert isinstance(result, Timedelta)\n assert result == Timedelta(-239, unit="h")\n\n def test_td_sub_timedeltalike_object_dtype_array(self):\n # GH#21980\n arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")])\n exp = np.array([Timestamp("20121231 9:01"), Timestamp("20121229 9:02")])\n res = arr - Timedelta("1D")\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_sub_mixed_most_timedeltalike_object_dtype_array(self):\n # GH#21980\n now = Timestamp("2021-11-09 09:54:00")\n arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")])\n exp = np.array(\n [\n now - Timedelta("1D"),\n Timedelta("0D"),\n np.timedelta64(2, "h") - Timedelta("1D"),\n ]\n )\n res = arr - Timedelta("1D")\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_rsub_mixed_most_timedeltalike_object_dtype_array(self):\n # GH#21980\n now = Timestamp("2021-11-09 09:54:00")\n arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")])\n msg = r"unsupported operand type\(s\) for \-: 'Timedelta' and 'Timestamp'"\n with pytest.raises(TypeError, match=msg):\n Timedelta("1D") - arr\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_timedeltalike_object_dtype_array(self, op):\n # GH#21980\n arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")])\n exp = np.array([Timestamp("20130102 9:01"), Timestamp("20121231 9:02")])\n res = op(arr, Timedelta("1D"))\n tm.assert_numpy_array_equal(res, exp)\n\n @pytest.mark.parametrize("op", [operator.add, ops.radd])\n def test_td_add_mixed_timedeltalike_object_dtype_array(self, op):\n # GH#21980\n now = Timestamp("2021-11-09 09:54:00")\n arr = np.array([now, Timedelta("1D")])\n exp = np.array([now + Timedelta("1D"), Timedelta("2D")])\n res = op(arr, Timedelta("1D"))\n tm.assert_numpy_array_equal(res, exp)\n\n def test_td_add_sub_td64_ndarray(self):\n td = Timedelta("1 day")\n\n other = np.array([td.to_timedelta64()])\n expected = np.array([Timedelta("2 Days").to_timedelta64()])\n\n result = td + other\n tm.assert_numpy_array_equal(result, expected)\n result = other + td\n tm.assert_numpy_array_equal(result, expected)\n\n result = td - other\n tm.assert_numpy_array_equal(result, expected * 0)\n result = other - td\n tm.assert_numpy_array_equal(result, expected * 0)\n\n def test_td_add_sub_dt64_ndarray(self):\n td = Timedelta("1 day")\n other = np.array(["2000-01-01"], dtype="M8[ns]")\n\n expected = np.array(["2000-01-02"], dtype="M8[ns]")\n tm.assert_numpy_array_equal(td + other, expected)\n tm.assert_numpy_array_equal(other + td, expected)\n\n expected = np.array(["1999-12-31"], dtype="M8[ns]")\n tm.assert_numpy_array_equal(-td + other, expected)\n tm.assert_numpy_array_equal(other - td, expected)\n\n def test_td_add_sub_ndarray_0d(self):\n td = Timedelta("1 day")\n other = np.array(td.asm8)\n\n result = td + other\n assert isinstance(result, Timedelta)\n assert result == 2 * td\n\n result = other + td\n assert isinstance(result, Timedelta)\n assert result == 2 * td\n\n result = other - td\n assert isinstance(result, Timedelta)\n assert result == 0 * td\n\n result = td - other\n assert isinstance(result, Timedelta)\n assert result == 0 * td\n\n\nclass TestTimedeltaMultiplicationDivision:\n """\n Tests for Timedelta methods:\n\n __mul__, __rmul__,\n __div__, __rdiv__,\n __truediv__, __rtruediv__,\n __floordiv__, __rfloordiv__,\n __mod__, __rmod__,\n __divmod__, __rdivmod__\n """\n\n # ---------------------------------------------------------------\n # Timedelta.__mul__, __rmul__\n\n @pytest.mark.parametrize(\n "td_nat", [NaT, np.timedelta64("NaT", "ns"), np.timedelta64("NaT")]\n )\n @pytest.mark.parametrize("op", [operator.mul, ops.rmul])\n def test_td_mul_nat(self, op, td_nat):\n # GH#19819\n td = Timedelta(10, unit="d")\n typs = "|".join(["numpy.timedelta64", "NaTType", "Timedelta"])\n msg = "|".join(\n [\n rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'",\n r"ufunc '?multiply'? cannot use operands with types",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n op(td, td_nat)\n\n @pytest.mark.parametrize("nan", [np.nan, np.float64("NaN"), float("nan")])\n @pytest.mark.parametrize("op", [operator.mul, ops.rmul])\n def test_td_mul_nan(self, op, nan):\n # np.float64('NaN') has a 'dtype' attr, avoid treating as array\n td = Timedelta(10, unit="d")\n result = op(td, nan)\n assert result is NaT\n\n @pytest.mark.parametrize("op", [operator.mul, ops.rmul])\n def test_td_mul_scalar(self, op):\n # GH#19738\n td = Timedelta(minutes=3)\n\n result = op(td, 2)\n assert result == Timedelta(minutes=6)\n\n result = op(td, 1.5)\n assert result == Timedelta(minutes=4, seconds=30)\n\n assert op(td, np.nan) is NaT\n\n assert op(-1, td)._value == -1 * td._value\n assert op(-1.0, td)._value == -1.0 * td._value\n\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n # timedelta * datetime is gibberish\n op(td, Timestamp(2016, 1, 2))\n\n with pytest.raises(TypeError, match=msg):\n # invalid multiply with another timedelta\n op(td, td)\n\n def test_td_mul_numeric_ndarray(self):\n td = Timedelta("1 day")\n other = np.array([2])\n expected = np.array([Timedelta("2 Days").to_timedelta64()])\n\n result = td * other\n tm.assert_numpy_array_equal(result, expected)\n\n result = other * td\n tm.assert_numpy_array_equal(result, expected)\n\n def test_td_mul_numeric_ndarray_0d(self):\n td = Timedelta("1 day")\n other = np.array(2, dtype=np.int64)\n assert other.ndim == 0\n expected = Timedelta("2 days")\n\n res = td * other\n assert type(res) is Timedelta\n assert res == expected\n\n res = other * td\n assert type(res) is Timedelta\n assert res == expected\n\n def test_td_mul_td64_ndarray_invalid(self):\n td = Timedelta("1 day")\n other = np.array([Timedelta("2 Days").to_timedelta64()])\n\n msg = (\n "ufunc '?multiply'? cannot use operands with types "\n rf"dtype\('{tm.ENDIAN}m8\[ns\]'\) and dtype\('{tm.ENDIAN}m8\[ns\]'\)"\n )\n with pytest.raises(TypeError, match=msg):\n td * other\n with pytest.raises(TypeError, match=msg):\n other * td\n\n # ---------------------------------------------------------------\n # Timedelta.__div__, __truediv__\n\n def test_td_div_timedeltalike_scalar(self):\n # GH#19738\n td = Timedelta(10, unit="d")\n\n result = td / offsets.Hour(1)\n assert result == 240\n\n assert td / td == 1\n assert td / np.timedelta64(60, "h") == 4\n\n assert np.isnan(td / NaT)\n\n def test_td_div_td64_non_nano(self):\n # truediv\n td = Timedelta("1 days 2 hours 3 ns")\n result = td / np.timedelta64(1, "D")\n assert result == td._value / (86400 * 10**9)\n result = td / np.timedelta64(1, "s")\n assert result == td._value / 10**9\n result = td / np.timedelta64(1, "ns")\n assert result == td._value\n\n # floordiv\n td = Timedelta("1 days 2 hours 3 ns")\n result = td // np.timedelta64(1, "D")\n assert result == 1\n result = td // np.timedelta64(1, "s")\n assert result == 93600\n result = td // np.timedelta64(1, "ns")\n assert result == td._value\n\n def test_td_div_numeric_scalar(self):\n # GH#19738\n td = Timedelta(10, unit="d")\n\n result = td / 2\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=5)\n\n result = td / 5\n assert isinstance(result, Timedelta)\n assert result == Timedelta(days=2)\n\n @pytest.mark.parametrize(\n "nan",\n [\n np.nan,\n np.float64("NaN"),\n float("nan"),\n ],\n )\n def test_td_div_nan(self, nan):\n # np.float64('NaN') has a 'dtype' attr, avoid treating as array\n td = Timedelta(10, unit="d")\n result = td / nan\n assert result is NaT\n\n result = td // nan\n assert result is NaT\n\n def test_td_div_td64_ndarray(self):\n td = Timedelta("1 day")\n\n other = np.array([Timedelta("2 Days").to_timedelta64()])\n expected = np.array([0.5])\n\n result = td / other\n tm.assert_numpy_array_equal(result, expected)\n\n result = other / td\n tm.assert_numpy_array_equal(result, expected * 4)\n\n def test_td_div_ndarray_0d(self):\n td = Timedelta("1 day")\n\n other = np.array(1)\n res = td / other\n assert isinstance(res, Timedelta)\n assert res == td\n\n # ---------------------------------------------------------------\n # Timedelta.__rdiv__\n\n def test_td_rdiv_timedeltalike_scalar(self):\n # GH#19738\n td = Timedelta(10, unit="d")\n result = offsets.Hour(1) / td\n assert result == 1 / 240.0\n\n assert np.timedelta64(60, "h") / td == 0.25\n\n def test_td_rdiv_na_scalar(self):\n # GH#31869 None gets cast to NaT\n td = Timedelta(10, unit="d")\n\n result = NaT / td\n assert np.isnan(result)\n\n result = None / td\n assert np.isnan(result)\n\n result = np.timedelta64("NaT") / td\n assert np.isnan(result)\n\n msg = r"unsupported operand type\(s\) for /: 'numpy.datetime64' and 'Timedelta'"\n with pytest.raises(TypeError, match=msg):\n np.datetime64("NaT") / td\n\n msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"\n with pytest.raises(TypeError, match=msg):\n np.nan / td\n\n def test_td_rdiv_ndarray(self):\n td = Timedelta(10, unit="d")\n\n arr = np.array([td], dtype=object)\n result = arr / td\n expected = np.array([1], dtype=np.float64)\n tm.assert_numpy_array_equal(result, expected)\n\n arr = np.array([None])\n result = arr / td\n expected = np.array([np.nan])\n tm.assert_numpy_array_equal(result, expected)\n\n arr = np.array([np.nan], dtype=object)\n msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"\n with pytest.raises(TypeError, match=msg):\n arr / td\n\n arr = np.array([np.nan], dtype=np.float64)\n msg = "cannot use operands with types dtype"\n with pytest.raises(TypeError, match=msg):\n arr / td\n\n def test_td_rdiv_ndarray_0d(self):\n td = Timedelta(10, unit="d")\n\n arr = np.array(td.asm8)\n\n assert arr / td == 1\n\n # ---------------------------------------------------------------\n # Timedelta.__floordiv__\n\n def test_td_floordiv_timedeltalike_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n scalar = Timedelta(hours=3, minutes=3)\n\n assert td // scalar == 1\n assert -td // scalar.to_pytimedelta() == -2\n assert (2 * td) // scalar.to_timedelta64() == 2\n\n def test_td_floordiv_null_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n assert td // np.nan is NaT\n assert np.isnan(td // NaT)\n assert np.isnan(td // np.timedelta64("NaT"))\n\n def test_td_floordiv_offsets(self):\n # GH#19738\n td = Timedelta(hours=3, minutes=4)\n assert td // offsets.Hour(1) == 3\n assert td // offsets.Minute(2) == 92\n\n def test_td_floordiv_invalid_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n msg = "|".join(\n [\n r"Invalid dtype datetime64\[D\] for __floordiv__",\n "'dtype' is an invalid keyword argument for this function",\n "this function got an unexpected keyword argument 'dtype'",\n r"ufunc '?floor_divide'? cannot use operands with types",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n td // np.datetime64("2016-01-01", dtype="datetime64[us]")\n\n def test_td_floordiv_numeric_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n\n expected = Timedelta(hours=1, minutes=32)\n assert td // 2 == expected\n assert td // 2.0 == expected\n assert td // np.float64(2.0) == expected\n assert td // np.int32(2.0) == expected\n assert td // np.uint8(2.0) == expected\n\n def test_td_floordiv_timedeltalike_array(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n scalar = Timedelta(hours=3, minutes=3)\n\n # Array-like others\n assert td // np.array(scalar.to_timedelta64()) == 1\n\n res = (3 * td) // np.array([scalar.to_timedelta64()])\n expected = np.array([3], dtype=np.int64)\n tm.assert_numpy_array_equal(res, expected)\n\n res = (10 * td) // np.array([scalar.to_timedelta64(), np.timedelta64("NaT")])\n expected = np.array([10, np.nan])\n tm.assert_numpy_array_equal(res, expected)\n\n def test_td_floordiv_numeric_series(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=4)\n ser = pd.Series([1], dtype=np.int64)\n res = td // ser\n assert res.dtype.kind == "m"\n\n # ---------------------------------------------------------------\n # Timedelta.__rfloordiv__\n\n def test_td_rfloordiv_timedeltalike_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n scalar = Timedelta(hours=3, minutes=4)\n\n # scalar others\n # x // Timedelta is defined only for timedelta-like x. int-like,\n # float-like, and date-like, in particular, should all either\n # a) raise TypeError directly or\n # b) return NotImplemented, following which the reversed\n # operation will raise TypeError.\n assert td.__rfloordiv__(scalar) == 1\n assert (-td).__rfloordiv__(scalar.to_pytimedelta()) == -2\n assert (2 * td).__rfloordiv__(scalar.to_timedelta64()) == 0\n\n def test_td_rfloordiv_null_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n assert np.isnan(td.__rfloordiv__(NaT))\n assert np.isnan(td.__rfloordiv__(np.timedelta64("NaT")))\n\n def test_td_rfloordiv_offsets(self):\n # GH#19738\n assert offsets.Hour(1) // Timedelta(minutes=25) == 2\n\n def test_td_rfloordiv_invalid_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n dt64 = np.datetime64("2016-01-01", "us")\n\n assert td.__rfloordiv__(dt64) is NotImplemented\n\n msg = (\n r"unsupported operand type\(s\) for //: 'numpy.datetime64' and 'Timedelta'"\n )\n with pytest.raises(TypeError, match=msg):\n dt64 // td\n\n def test_td_rfloordiv_numeric_scalar(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n\n assert td.__rfloordiv__(np.nan) is NotImplemented\n assert td.__rfloordiv__(3.5) is NotImplemented\n assert td.__rfloordiv__(2) is NotImplemented\n assert td.__rfloordiv__(np.float64(2.0)) is NotImplemented\n assert td.__rfloordiv__(np.uint8(9)) is NotImplemented\n assert td.__rfloordiv__(np.int32(2.0)) is NotImplemented\n\n msg = r"unsupported operand type\(s\) for //: '.*' and 'Timedelta"\n with pytest.raises(TypeError, match=msg):\n np.float64(2.0) // td\n with pytest.raises(TypeError, match=msg):\n np.uint8(9) // td\n with pytest.raises(TypeError, match=msg):\n # deprecated GH#19761, enforced GH#29797\n np.int32(2.0) // td\n\n def test_td_rfloordiv_timedeltalike_array(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n scalar = Timedelta(hours=3, minutes=4)\n\n # Array-like others\n assert td.__rfloordiv__(np.array(scalar.to_timedelta64())) == 1\n\n res = td.__rfloordiv__(np.array([(3 * scalar).to_timedelta64()]))\n expected = np.array([3], dtype=np.int64)\n tm.assert_numpy_array_equal(res, expected)\n\n arr = np.array([(10 * scalar).to_timedelta64(), np.timedelta64("NaT")])\n res = td.__rfloordiv__(arr)\n expected = np.array([10, np.nan])\n tm.assert_numpy_array_equal(res, expected)\n\n def test_td_rfloordiv_intarray(self):\n # deprecated GH#19761, enforced GH#29797\n ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10**9\n\n msg = "Invalid dtype"\n with pytest.raises(TypeError, match=msg):\n ints // Timedelta(1, unit="s")\n\n def test_td_rfloordiv_numeric_series(self):\n # GH#18846\n td = Timedelta(hours=3, minutes=3)\n ser = pd.Series([1], dtype=np.int64)\n res = td.__rfloordiv__(ser)\n assert res is NotImplemented\n\n msg = "Invalid dtype"\n with pytest.raises(TypeError, match=msg):\n # Deprecated GH#19761, enforced GH#29797\n ser // td\n\n # ----------------------------------------------------------------\n # Timedelta.__mod__, __rmod__\n\n def test_mod_timedeltalike(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n # Timedelta-like others\n result = td % Timedelta(hours=6)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=1)\n\n result = td % timedelta(minutes=60)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n result = td % NaT\n assert result is NaT\n\n def test_mod_timedelta64_nat(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % np.timedelta64("NaT", "ns")\n assert result is NaT\n\n def test_mod_timedelta64(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % np.timedelta64(2, "h")\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=1)\n\n def test_mod_offset(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n result = td % offsets.Hour(5)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(hours=2)\n\n def test_mod_numeric(self):\n # GH#19365\n td = Timedelta(hours=37)\n\n # Numeric Others\n result = td % 2\n assert isinstance(result, Timedelta)\n assert result == Timedelta(0)\n\n result = td % 1e12\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=3, seconds=20)\n\n result = td % int(1e12)\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=3, seconds=20)\n\n def test_mod_invalid(self):\n # GH#19365\n td = Timedelta(hours=37)\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n td % Timestamp("2018-01-22")\n\n with pytest.raises(TypeError, match=msg):\n td % []\n\n def test_rmod_pytimedelta(self):\n # GH#19365\n td = Timedelta(minutes=3)\n\n result = timedelta(minutes=4) % td\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=1)\n\n def test_rmod_timedelta64(self):\n # GH#19365\n td = Timedelta(minutes=3)\n result = np.timedelta64(5, "m") % td\n assert isinstance(result, Timedelta)\n assert result == Timedelta(minutes=2)\n\n def test_rmod_invalid(self):\n # GH#19365\n td = Timedelta(minutes=3)\n\n msg = "unsupported operand"\n with pytest.raises(TypeError, match=msg):\n Timestamp("2018-01-22") % td\n\n with pytest.raises(TypeError, match=msg):\n 15 % td\n\n with pytest.raises(TypeError, match=msg):\n 16.0 % td\n\n msg = "Invalid dtype int"\n with pytest.raises(TypeError, match=msg):\n np.array([22, 24]) % td\n\n # ----------------------------------------------------------------\n # Timedelta.__divmod__, __rdivmod__\n\n def test_divmod_numeric(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, 53 * 3600 * 1e9)\n assert result[0] == Timedelta(1, unit="ns")\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=1)\n\n assert result\n result = divmod(td, np.nan)\n assert result[0] is NaT\n assert result[1] is NaT\n\n def test_divmod(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, timedelta(days=1))\n assert result[0] == 2\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=6)\n\n result = divmod(td, 54)\n assert result[0] == Timedelta(hours=1)\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(0)\n\n result = divmod(td, NaT)\n assert np.isnan(result[0])\n assert result[1] is NaT\n\n def test_divmod_offset(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n result = divmod(td, offsets.Hour(-4))\n assert result[0] == -14\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=-2)\n\n def test_divmod_invalid(self):\n # GH#19365\n td = Timedelta(days=2, hours=6)\n\n msg = r"unsupported operand type\(s\) for //: 'Timedelta' and 'Timestamp'"\n with pytest.raises(TypeError, match=msg):\n divmod(td, Timestamp("2018-01-22"))\n\n def test_rdivmod_pytimedelta(self):\n # GH#19365\n result = divmod(timedelta(days=2, hours=6), Timedelta(days=1))\n assert result[0] == 2\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=6)\n\n def test_rdivmod_offset(self):\n result = divmod(offsets.Hour(54), Timedelta(hours=-4))\n assert result[0] == -14\n assert isinstance(result[1], Timedelta)\n assert result[1] == Timedelta(hours=-2)\n\n def test_rdivmod_invalid(self):\n # GH#19365\n td = Timedelta(minutes=3)\n msg = "unsupported operand type"\n\n with pytest.raises(TypeError, match=msg):\n divmod(Timestamp("2018-01-22"), td)\n\n with pytest.raises(TypeError, match=msg):\n divmod(15, td)\n\n with pytest.raises(TypeError, match=msg):\n divmod(16.0, td)\n\n msg = "Invalid dtype int"\n with pytest.raises(TypeError, match=msg):\n divmod(np.array([22, 24]), td)\n\n # ----------------------------------------------------------------\n\n @pytest.mark.parametrize(\n "op", [operator.mul, ops.rmul, operator.truediv, ops.rdiv, ops.rsub]\n )\n @pytest.mark.parametrize(\n "arr",\n [\n np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]),\n np.array([Timestamp("2021-11-09 09:54:00"), Timedelta("1D")]),\n ],\n )\n def test_td_op_timedelta_timedeltalike_array(self, op, arr):\n msg = "unsupported operand type|cannot use operands with types"\n with pytest.raises(TypeError, match=msg):\n op(arr, Timedelta("1D"))\n\n\nclass TestTimedeltaComparison:\n @pytest.mark.skip_ubsan\n def test_compare_pytimedelta_bounds(self):\n # GH#49021 don't overflow on comparison with very large pytimedeltas\n\n for unit in ["ns", "us"]:\n tdmax = Timedelta.max.as_unit(unit).max\n tdmin = Timedelta.min.as_unit(unit).min\n\n assert tdmax < timedelta.max\n assert tdmax <= timedelta.max\n assert not tdmax > timedelta.max\n assert not tdmax >= timedelta.max\n assert tdmax != timedelta.max\n assert not tdmax == timedelta.max\n\n assert tdmin > timedelta.min\n assert tdmin >= timedelta.min\n assert not tdmin < timedelta.min\n assert not tdmin <= timedelta.min\n assert tdmin != timedelta.min\n assert not tdmin == timedelta.min\n\n # But the "ms" and "s"-reso bounds extend pass pytimedelta\n for unit in ["ms", "s"]:\n tdmax = Timedelta.max.as_unit(unit).max\n tdmin = Timedelta.min.as_unit(unit).min\n\n assert tdmax > timedelta.max\n assert tdmax >= timedelta.max\n assert not tdmax < timedelta.max\n assert not tdmax <= timedelta.max\n assert tdmax != timedelta.max\n assert not tdmax == timedelta.max\n\n assert tdmin < timedelta.min\n assert tdmin <= timedelta.min\n assert not tdmin > timedelta.min\n assert not tdmin >= timedelta.min\n assert tdmin != timedelta.min\n assert not tdmin == timedelta.min\n\n def test_compare_pytimedelta_bounds2(self):\n # a pytimedelta outside the microsecond bounds\n pytd = timedelta(days=999999999, seconds=86399)\n # NB: np.timedelta64(td, "s"") incorrectly overflows\n td64 = np.timedelta64(pytd.days, "D") + np.timedelta64(pytd.seconds, "s")\n td = Timedelta(td64)\n assert td.days == pytd.days\n assert td.seconds == pytd.seconds\n\n assert td == pytd\n assert not td != pytd\n assert not td < pytd\n assert not td > pytd\n assert td <= pytd\n assert td >= pytd\n\n td2 = td - Timedelta(seconds=1).as_unit("s")\n assert td2 != pytd\n assert not td2 == pytd\n assert td2 < pytd\n assert td2 <= pytd\n assert not td2 > pytd\n assert not td2 >= pytd\n\n def test_compare_tick(self, tick_classes):\n cls = tick_classes\n\n off = cls(4)\n td = off._as_pd_timedelta\n assert isinstance(td, Timedelta)\n\n assert td == off\n assert not td != off\n assert td <= off\n assert td >= off\n assert not td < off\n assert not td > off\n\n assert not td == 2 * off\n assert td != 2 * off\n assert td <= 2 * off\n assert td < 2 * off\n assert not td >= 2 * off\n assert not td > 2 * off\n\n def test_comparison_object_array(self):\n # analogous to GH#15183\n td = Timedelta("2 days")\n other = Timedelta("3 hours")\n\n arr = np.array([other, td], dtype=object)\n res = arr == td\n expected = np.array([False, True], dtype=bool)\n assert (res == expected).all()\n\n # 2D case\n arr = np.array([[other, td], [td, other]], dtype=object)\n res = arr != td\n expected = np.array([[True, False], [False, True]], dtype=bool)\n assert res.shape == expected.shape\n assert (res == expected).all()\n\n def test_compare_timedelta_ndarray(self):\n # GH#11835\n periods = [Timedelta("0 days 01:00:00"), Timedelta("0 days 01:00:00")]\n arr = np.array(periods)\n result = arr[0] > arr\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_td64_ndarray(self):\n # GG#33441\n arr = np.arange(5).astype("timedelta64[ns]")\n td = Timedelta(arr[1])\n\n expected = np.array([False, True, False, False, False], dtype=bool)\n\n result = td == arr\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr == td\n tm.assert_numpy_array_equal(result, expected)\n\n result = td != arr\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = arr != td\n tm.assert_numpy_array_equal(result, ~expected)\n\n def test_compare_custom_object(self):\n """\n Make sure non supported operations on Timedelta returns NonImplemented\n and yields to other operand (GH#20829).\n """\n\n class CustomClass:\n def __init__(self, cmp_result=None) -> None:\n self.cmp_result = cmp_result\n\n def generic_result(self):\n if self.cmp_result is None:\n return NotImplemented\n else:\n return self.cmp_result\n\n def __eq__(self, other):\n return self.generic_result()\n\n def __gt__(self, other):\n return self.generic_result()\n\n t = Timedelta("1s")\n\n assert t != "string"\n assert t != 1\n assert t != CustomClass()\n assert t != CustomClass(cmp_result=False)\n\n assert t < CustomClass(cmp_result=True)\n assert not t < CustomClass(cmp_result=False)\n\n assert t == CustomClass(cmp_result=True)\n\n @pytest.mark.parametrize("val", ["string", 1])\n def test_compare_unknown_type(self, val):\n # GH#20829\n t = Timedelta("1s")\n msg = "not supported between instances of 'Timedelta' and '(int|str)'"\n with pytest.raises(TypeError, match=msg):\n t >= val\n with pytest.raises(TypeError, match=msg):\n t > val\n with pytest.raises(TypeError, match=msg):\n t <= val\n with pytest.raises(TypeError, match=msg):\n t < val\n\n\ndef test_ops_notimplemented():\n class Other:\n pass\n\n other = Other()\n\n td = Timedelta("1 day")\n assert td.__add__(other) is NotImplemented\n assert td.__sub__(other) is NotImplemented\n assert td.__truediv__(other) is NotImplemented\n assert td.__mul__(other) is NotImplemented\n assert td.__floordiv__(other) is NotImplemented\n\n\ndef test_ops_error_str():\n # GH#13624\n td = Timedelta("1 day")\n\n for left, right in [(td, "a"), ("a", td)]:\n msg = "|".join(\n [\n "unsupported operand type",\n r'can only concatenate str \(not "Timedelta"\) to str',\n "must be str, not Timedelta",\n ]\n )\n with pytest.raises(TypeError, match=msg):\n left + right\n\n msg = "not supported between instances of"\n with pytest.raises(TypeError, match=msg):\n left > right\n\n assert not left == right # pylint: disable=unneeded-not\n assert left != right\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\test_arithmetic.py
test_arithmetic.py
Python
38,156
0.95
0.101437
0.097872
node-utils
416
2024-07-16T21:58:13.825544
Apache-2.0
true
62859688f1f41300808013bbaf4e1af4
from datetime import timedelta\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nfrom pandas._libs.tslibs import OutOfBoundsTimedelta\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\n\nfrom pandas import (\n Index,\n NaT,\n Timedelta,\n TimedeltaIndex,\n offsets,\n to_timedelta,\n)\nimport pandas._testing as tm\n\n\nclass TestTimedeltaConstructorUnitKeyword:\n @pytest.mark.parametrize("unit", ["Y", "y", "M"])\n def test_unit_m_y_raises(self, unit):\n msg = "Units 'M', 'Y', and 'y' are no longer supported"\n\n with pytest.raises(ValueError, match=msg):\n Timedelta(10, unit)\n\n with pytest.raises(ValueError, match=msg):\n to_timedelta(10, unit)\n\n with pytest.raises(ValueError, match=msg):\n to_timedelta([1, 2], unit)\n\n @pytest.mark.parametrize(\n "unit,unit_depr",\n [\n ("h", "H"),\n ("min", "T"),\n ("s", "S"),\n ("ms", "L"),\n ("ns", "N"),\n ("us", "U"),\n ],\n )\n def test_units_H_T_S_L_N_U_deprecated(self, unit, unit_depr):\n # GH#52536\n msg = f"'{unit_depr}' is deprecated and will be removed in a future version."\n\n expected = Timedelta(1, unit=unit)\n with tm.assert_produces_warning(FutureWarning, match=msg):\n result = Timedelta(1, unit=unit_depr)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize(\n "unit, np_unit",\n [(value, "W") for value in ["W", "w"]]\n + [(value, "D") for value in ["D", "d", "days", "day", "Days", "Day"]]\n + [\n (value, "m")\n for value in [\n "m",\n "minute",\n "min",\n "minutes",\n "Minute",\n "Min",\n "Minutes",\n ]\n ]\n + [\n (value, "s")\n for value in [\n "s",\n "seconds",\n "sec",\n "second",\n "Seconds",\n "Sec",\n "Second",\n ]\n ]\n + [\n (value, "ms")\n for value in [\n "ms",\n "milliseconds",\n "millisecond",\n "milli",\n "millis",\n "MS",\n "Milliseconds",\n "Millisecond",\n "Milli",\n "Millis",\n ]\n ]\n + [\n (value, "us")\n for value in [\n "us",\n "microseconds",\n "microsecond",\n "micro",\n "micros",\n "u",\n "US",\n "Microseconds",\n "Microsecond",\n "Micro",\n "Micros",\n "U",\n ]\n ]\n + [\n (value, "ns")\n for value in [\n "ns",\n "nanoseconds",\n "nanosecond",\n "nano",\n "nanos",\n "n",\n "NS",\n "Nanoseconds",\n "Nanosecond",\n "Nano",\n "Nanos",\n "N",\n ]\n ],\n )\n @pytest.mark.parametrize("wrapper", [np.array, list, Index])\n def test_unit_parser(self, unit, np_unit, wrapper):\n # validate all units, GH 6855, GH 21762\n # array-likes\n expected = TimedeltaIndex(\n [np.timedelta64(i, np_unit) for i in np.arange(5).tolist()],\n dtype="m8[ns]",\n )\n # TODO(2.0): the desired output dtype may have non-nano resolution\n msg = f"'{unit}' is deprecated and will be removed in a future version."\n\n if (unit, np_unit) in (("u", "us"), ("U", "us"), ("n", "ns"), ("N", "ns")):\n warn = FutureWarning\n else:\n warn = FutureWarning\n msg = "The 'unit' keyword in TimedeltaIndex construction is deprecated"\n with tm.assert_produces_warning(warn, match=msg):\n result = to_timedelta(wrapper(range(5)), unit=unit)\n tm.assert_index_equal(result, expected)\n result = TimedeltaIndex(wrapper(range(5)), unit=unit)\n tm.assert_index_equal(result, expected)\n\n str_repr = [f"{x}{unit}" for x in np.arange(5)]\n result = to_timedelta(wrapper(str_repr))\n tm.assert_index_equal(result, expected)\n result = to_timedelta(wrapper(str_repr))\n tm.assert_index_equal(result, expected)\n\n # scalar\n expected = Timedelta(np.timedelta64(2, np_unit).astype("timedelta64[ns]"))\n result = to_timedelta(2, unit=unit)\n assert result == expected\n result = Timedelta(2, unit=unit)\n assert result == expected\n\n result = to_timedelta(f"2{unit}")\n assert result == expected\n result = Timedelta(f"2{unit}")\n assert result == expected\n\n\ndef test_construct_from_kwargs_overflow():\n # GH#55503\n msg = "seconds=86400000000000000000, milliseconds=0, microseconds=0, nanoseconds=0"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(days=10**6)\n msg = "seconds=60000000000000000000, milliseconds=0, microseconds=0, nanoseconds=0"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(minutes=10**9)\n\n\ndef test_construct_with_weeks_unit_overflow():\n # GH#47268 don't silently wrap around\n with pytest.raises(OutOfBoundsTimedelta, match="without overflow"):\n Timedelta(1000000000000000000, unit="W")\n\n with pytest.raises(OutOfBoundsTimedelta, match="without overflow"):\n Timedelta(1000000000000000000.0, unit="W")\n\n\ndef test_construct_from_td64_with_unit():\n # ignore the unit, as it may cause silently overflows leading to incorrect\n # results, and in non-overflow cases is irrelevant GH#46827\n obj = np.timedelta64(123456789000000000, "h")\n\n with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):\n Timedelta(obj, unit="ps")\n\n with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):\n Timedelta(obj, unit="ns")\n\n with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):\n Timedelta(obj)\n\n\ndef test_from_td64_retain_resolution():\n # case where we retain millisecond resolution\n obj = np.timedelta64(12345, "ms")\n\n td = Timedelta(obj)\n assert td._value == obj.view("i8")\n assert td._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n # Case where we cast to nearest-supported reso\n obj2 = np.timedelta64(1234, "D")\n td2 = Timedelta(obj2)\n assert td2._creso == NpyDatetimeUnit.NPY_FR_s.value\n assert td2 == obj2\n assert td2.days == 1234\n\n # Case that _would_ overflow if we didn't support non-nano\n obj3 = np.timedelta64(1000000000000000000, "us")\n td3 = Timedelta(obj3)\n assert td3.total_seconds() == 1000000000000\n assert td3._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n\ndef test_from_pytimedelta_us_reso():\n # pytimedelta has microsecond resolution, so Timedelta(pytd) inherits that\n td = timedelta(days=4, minutes=3)\n result = Timedelta(td)\n assert result.to_pytimedelta() == td\n assert result._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n\ndef test_from_tick_reso():\n tick = offsets.Nano()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n tick = offsets.Micro()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n tick = offsets.Milli()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n tick = offsets.Second()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n # everything above Second gets cast to the closest supported reso: second\n tick = offsets.Minute()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n tick = offsets.Hour()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n tick = offsets.Day()\n assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n\ndef test_construction():\n expected = np.timedelta64(10, "D").astype("m8[ns]").view("i8")\n assert Timedelta(10, unit="d")._value == expected\n assert Timedelta(10.0, unit="d")._value == expected\n assert Timedelta("10 days")._value == expected\n assert Timedelta(days=10)._value == expected\n assert Timedelta(days=10.0)._value == expected\n\n expected += np.timedelta64(10, "s").astype("m8[ns]").view("i8")\n assert Timedelta("10 days 00:00:10")._value == expected\n assert Timedelta(days=10, seconds=10)._value == expected\n assert Timedelta(days=10, milliseconds=10 * 1000)._value == expected\n assert Timedelta(days=10, microseconds=10 * 1000 * 1000)._value == expected\n\n # rounding cases\n assert Timedelta(82739999850000)._value == 82739999850000\n assert "0 days 22:58:59.999850" in str(Timedelta(82739999850000))\n assert Timedelta(123072001000000)._value == 123072001000000\n assert "1 days 10:11:12.001" in str(Timedelta(123072001000000))\n\n # string conversion with/without leading zero\n # GH#9570\n assert Timedelta("0:00:00") == timedelta(hours=0)\n assert Timedelta("00:00:00") == timedelta(hours=0)\n assert Timedelta("-1:00:00") == -timedelta(hours=1)\n assert Timedelta("-01:00:00") == -timedelta(hours=1)\n\n # more strings & abbrevs\n # GH#8190\n assert Timedelta("1 h") == timedelta(hours=1)\n assert Timedelta("1 hour") == timedelta(hours=1)\n assert Timedelta("1 hr") == timedelta(hours=1)\n assert Timedelta("1 hours") == timedelta(hours=1)\n assert Timedelta("-1 hours") == -timedelta(hours=1)\n assert Timedelta("1 m") == timedelta(minutes=1)\n assert Timedelta("1.5 m") == timedelta(seconds=90)\n assert Timedelta("1 minute") == timedelta(minutes=1)\n assert Timedelta("1 minutes") == timedelta(minutes=1)\n assert Timedelta("1 s") == timedelta(seconds=1)\n assert Timedelta("1 second") == timedelta(seconds=1)\n assert Timedelta("1 seconds") == timedelta(seconds=1)\n assert Timedelta("1 ms") == timedelta(milliseconds=1)\n assert Timedelta("1 milli") == timedelta(milliseconds=1)\n assert Timedelta("1 millisecond") == timedelta(milliseconds=1)\n assert Timedelta("1 us") == timedelta(microseconds=1)\n assert Timedelta("1 µs") == timedelta(microseconds=1)\n assert Timedelta("1 micros") == timedelta(microseconds=1)\n assert Timedelta("1 microsecond") == timedelta(microseconds=1)\n assert Timedelta("1.5 microsecond") == Timedelta("00:00:00.000001500")\n assert Timedelta("1 ns") == Timedelta("00:00:00.000000001")\n assert Timedelta("1 nano") == Timedelta("00:00:00.000000001")\n assert Timedelta("1 nanosecond") == Timedelta("00:00:00.000000001")\n\n # combos\n assert Timedelta("10 days 1 hour") == timedelta(days=10, hours=1)\n assert Timedelta("10 days 1 h") == timedelta(days=10, hours=1)\n assert Timedelta("10 days 1 h 1m 1s") == timedelta(\n days=10, hours=1, minutes=1, seconds=1\n )\n assert Timedelta("-10 days 1 h 1m 1s") == -timedelta(\n days=10, hours=1, minutes=1, seconds=1\n )\n assert Timedelta("-10 days 1 h 1m 1s") == -timedelta(\n days=10, hours=1, minutes=1, seconds=1\n )\n assert Timedelta("-10 days 1 h 1m 1s 3us") == -timedelta(\n days=10, hours=1, minutes=1, seconds=1, microseconds=3\n )\n assert Timedelta("-10 days 1 h 1.5m 1s 3us") == -timedelta(\n days=10, hours=1, minutes=1, seconds=31, microseconds=3\n )\n\n # Currently invalid as it has a - on the hh:mm:dd part\n # (only allowed on the days)\n msg = "only leading negative signs are allowed"\n with pytest.raises(ValueError, match=msg):\n Timedelta("-10 days -1 h 1.5m 1s 3us")\n\n # only leading neg signs are allowed\n with pytest.raises(ValueError, match=msg):\n Timedelta("10 days -1 h 1.5m 1s 3us")\n\n # no units specified\n msg = "no units specified"\n with pytest.raises(ValueError, match=msg):\n Timedelta("3.1415")\n\n # invalid construction\n msg = "cannot construct a Timedelta"\n with pytest.raises(ValueError, match=msg):\n Timedelta()\n\n msg = "unit abbreviation w/o a number"\n with pytest.raises(ValueError, match=msg):\n Timedelta("foo")\n\n msg = (\n "cannot construct a Timedelta from "\n "the passed arguments, allowed keywords are "\n )\n with pytest.raises(ValueError, match=msg):\n Timedelta(day=10)\n\n # floats\n expected = np.timedelta64(10, "s").astype("m8[ns]").view("i8") + np.timedelta64(\n 500, "ms"\n ).astype("m8[ns]").view("i8")\n assert Timedelta(10.5, unit="s")._value == expected\n\n # offset\n assert to_timedelta(offsets.Hour(2)) == Timedelta(hours=2)\n assert Timedelta(offsets.Hour(2)) == Timedelta(hours=2)\n assert Timedelta(offsets.Second(2)) == Timedelta(seconds=2)\n\n # GH#11995: unicode\n expected = Timedelta("1h")\n result = Timedelta("1h")\n assert result == expected\n assert to_timedelta(offsets.Hour(2)) == Timedelta("0 days, 02:00:00")\n\n msg = "unit abbreviation w/o a number"\n with pytest.raises(ValueError, match=msg):\n Timedelta("foo bar")\n\n\n@pytest.mark.parametrize(\n "item",\n list(\n {\n "days": "D",\n "seconds": "s",\n "microseconds": "us",\n "milliseconds": "ms",\n "minutes": "m",\n "hours": "h",\n "weeks": "W",\n }.items()\n ),\n)\n@pytest.mark.parametrize(\n "npdtype", [np.int64, np.int32, np.int16, np.float64, np.float32, np.float16]\n)\ndef test_td_construction_with_np_dtypes(npdtype, item):\n # GH#8757: test construction with np dtypes\n pykwarg, npkwarg = item\n expected = np.timedelta64(1, npkwarg).astype("m8[ns]").view("i8")\n assert Timedelta(**{pykwarg: npdtype(1)})._value == expected\n\n\n@pytest.mark.parametrize(\n "val",\n [\n "1s",\n "-1s",\n "1us",\n "-1us",\n "1 day",\n "-1 day",\n "-23:59:59.999999",\n "-1 days +23:59:59.999999",\n "-1ns",\n "1ns",\n "-23:59:59.999999999",\n ],\n)\ndef test_td_from_repr_roundtrip(val):\n # round-trip both for string and value\n td = Timedelta(val)\n assert Timedelta(td._value) == td\n\n assert Timedelta(str(td)) == td\n assert Timedelta(td._repr_base(format="all")) == td\n assert Timedelta(td._repr_base()) == td\n\n\ndef test_overflow_on_construction():\n # GH#3374\n value = Timedelta("1day")._value * 20169940\n msg = "Cannot cast 1742682816000000000000 from ns to 'ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(value)\n\n # xref GH#17637\n msg = "Cannot cast 139993 from D to 'ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(7 * 19999, unit="D")\n\n # used to overflow before non-ns support\n td = Timedelta(timedelta(days=13 * 19999))\n assert td._creso == NpyDatetimeUnit.NPY_FR_us.value\n assert td.days == 13 * 19999\n\n\n@pytest.mark.parametrize(\n "val, unit",\n [\n (15251, "W"), # 1\n (106752, "D"), # change from previous:\n (2562048, "h"), # 0 hours\n (153722868, "m"), # 13 minutes\n (9223372037, "s"), # 44 seconds\n ],\n)\ndef test_construction_out_of_bounds_td64ns(val, unit):\n # TODO: parametrize over units just above/below the implementation bounds\n # once GH#38964 is resolved\n\n # Timedelta.max is just under 106752 days\n td64 = np.timedelta64(val, unit)\n assert td64.astype("m8[ns]").view("i8") < 0 # i.e. naive astype will be wrong\n\n td = Timedelta(td64)\n if unit != "M":\n # with unit="M" the conversion to "s" is poorly defined\n # (and numpy issues DeprecationWarning)\n assert td.asm8 == td64\n assert td.asm8.dtype == "m8[s]"\n msg = r"Cannot cast 1067\d\d days .* to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td.as_unit("ns")\n\n # But just back in bounds and we are OK\n assert Timedelta(td64 - 1) == td64 - 1\n\n td64 *= -1\n assert td64.astype("m8[ns]").view("i8") > 0 # i.e. naive astype will be wrong\n\n td2 = Timedelta(td64)\n msg = r"Cannot cast -1067\d\d days .* to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td2.as_unit("ns")\n\n # But just back in bounds and we are OK\n assert Timedelta(td64 + 1) == td64 + 1\n\n\n@pytest.mark.parametrize(\n "val, unit",\n [\n (15251 * 10**9, "W"),\n (106752 * 10**9, "D"),\n (2562048 * 10**9, "h"),\n (153722868 * 10**9, "m"),\n ],\n)\ndef test_construction_out_of_bounds_td64s(val, unit):\n td64 = np.timedelta64(val, unit)\n with pytest.raises(OutOfBoundsTimedelta, match=str(td64)):\n Timedelta(td64)\n\n # But just back in bounds and we are OK\n assert Timedelta(td64 - 10**9) == td64 - 10**9\n\n\n@pytest.mark.parametrize(\n "fmt,exp",\n [\n (\n "P6DT0H50M3.010010012S",\n Timedelta(\n days=6,\n minutes=50,\n seconds=3,\n milliseconds=10,\n microseconds=10,\n nanoseconds=12,\n ),\n ),\n (\n "P-6DT0H50M3.010010012S",\n Timedelta(\n days=-6,\n minutes=50,\n seconds=3,\n milliseconds=10,\n microseconds=10,\n nanoseconds=12,\n ),\n ),\n ("P4DT12H30M5S", Timedelta(days=4, hours=12, minutes=30, seconds=5)),\n ("P0DT0H0M0.000000123S", Timedelta(nanoseconds=123)),\n ("P0DT0H0M0.00001S", Timedelta(microseconds=10)),\n ("P0DT0H0M0.001S", Timedelta(milliseconds=1)),\n ("P0DT0H1M0S", Timedelta(minutes=1)),\n ("P1DT25H61M61S", Timedelta(days=1, hours=25, minutes=61, seconds=61)),\n ("PT1S", Timedelta(seconds=1)),\n ("PT0S", Timedelta(seconds=0)),\n ("P1WT0S", Timedelta(days=7, seconds=0)),\n ("P1D", Timedelta(days=1)),\n ("P1DT1H", Timedelta(days=1, hours=1)),\n ("P1W", Timedelta(days=7)),\n ("PT300S", Timedelta(seconds=300)),\n ("P1DT0H0M00000000000S", Timedelta(days=1)),\n ("PT-6H3M", Timedelta(hours=-6, minutes=3)),\n ("-PT6H3M", Timedelta(hours=-6, minutes=-3)),\n ("-PT-6H+3M", Timedelta(hours=6, minutes=-3)),\n ],\n)\ndef test_iso_constructor(fmt, exp):\n assert Timedelta(fmt) == exp\n\n\n@pytest.mark.parametrize(\n "fmt",\n [\n "PPPPPPPPPPPP",\n "PDTHMS",\n "P0DT999H999M999S",\n "P1DT0H0M0.0000000000000S",\n "P1DT0H0M0.S",\n "P",\n "-P",\n ],\n)\ndef test_iso_constructor_raises(fmt):\n msg = f"Invalid ISO 8601 Duration format - {fmt}"\n with pytest.raises(ValueError, match=msg):\n Timedelta(fmt)\n\n\n@pytest.mark.parametrize(\n "constructed_td, conversion",\n [\n (Timedelta(nanoseconds=100), "100ns"),\n (\n Timedelta(\n days=1,\n hours=1,\n minutes=1,\n weeks=1,\n seconds=1,\n milliseconds=1,\n microseconds=1,\n nanoseconds=1,\n ),\n 694861001001001,\n ),\n (Timedelta(microseconds=1) + Timedelta(nanoseconds=1), "1us1ns"),\n (Timedelta(microseconds=1) - Timedelta(nanoseconds=1), "999ns"),\n (Timedelta(microseconds=1) + 5 * Timedelta(nanoseconds=-2), "990ns"),\n ],\n)\ndef test_td_constructor_on_nanoseconds(constructed_td, conversion):\n # GH#9273\n assert constructed_td == Timedelta(conversion)\n\n\ndef test_td_constructor_value_error():\n msg = "Invalid type <class 'str'>. Must be int or float."\n with pytest.raises(TypeError, match=msg):\n Timedelta(nanoseconds="abc")\n\n\ndef test_timedelta_constructor_identity():\n # Test for #30543\n expected = Timedelta(np.timedelta64(1, "s"))\n result = Timedelta(expected)\n assert result is expected\n\n\ndef test_timedelta_pass_td_and_kwargs_raises():\n # don't silently ignore the kwargs GH#48898\n td = Timedelta(days=1)\n msg = (\n "Cannot pass both a Timedelta input and timedelta keyword arguments, "\n r"got \['days'\]"\n )\n with pytest.raises(ValueError, match=msg):\n Timedelta(td, days=2)\n\n\n@pytest.mark.parametrize(\n "constructor, value, unit, expectation",\n [\n (Timedelta, "10s", "ms", (ValueError, "unit must not be specified")),\n (to_timedelta, "10s", "ms", (ValueError, "unit must not be specified")),\n (to_timedelta, ["1", 2, 3], "s", (ValueError, "unit must not be specified")),\n ],\n)\ndef test_string_with_unit(constructor, value, unit, expectation):\n exp, match = expectation\n with pytest.raises(exp, match=match):\n _ = constructor(value, unit=unit)\n\n\n@pytest.mark.parametrize(\n "value",\n [\n "".join(elements)\n for repetition in (1, 2)\n for elements in product("+-, ", repeat=repetition)\n ],\n)\ndef test_string_without_numbers(value):\n # GH39710 Timedelta input string with only symbols and no digits raises an error\n msg = (\n "symbols w/o a number"\n if value != "--"\n else "only leading negative signs are allowed"\n )\n with pytest.raises(ValueError, match=msg):\n Timedelta(value)\n\n\ndef test_timedelta_new_npnat():\n # GH#48898\n nat = np.timedelta64("NaT", "h")\n assert Timedelta(nat) is NaT\n\n\ndef test_subclass_respected():\n # GH#49579\n class MyCustomTimedelta(Timedelta):\n pass\n\n td = MyCustomTimedelta("1 minute")\n assert isinstance(td, MyCustomTimedelta)\n\n\ndef test_non_nano_value():\n # https://github.com/pandas-dev/pandas/issues/49076\n result = Timedelta(10, unit="D").as_unit("s").value\n # `.value` shows nanoseconds, even though unit is 's'\n assert result == 864000000000000\n\n # out-of-nanoseconds-bounds `.value` raises informative message\n msg = (\n r"Cannot convert Timedelta to nanoseconds without overflow. "\n r"Use `.asm8.view\('i8'\)` to cast represent Timedelta in its "\n r"own unit \(here, s\).$"\n )\n td = Timedelta(1_000, "D").as_unit("s") * 1_000\n with pytest.raises(OverflowError, match=msg):\n td.value\n # check that the suggested workaround actually works\n result = td.asm8.view("i8")\n assert result == 86400000000\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\test_constructors.py
test_constructors.py
Python
22,433
0.95
0.065903
0.085427
node-utils
230
2025-05-12T02:45:35.248968
Apache-2.0
true
5fefc5012defcdd9c7add7ec7f6016d2
import pytest\n\nfrom pandas import Timedelta\n\n\n@pytest.mark.parametrize(\n "td, expected_repr",\n [\n (Timedelta(10, unit="d"), "Timedelta('10 days 00:00:00')"),\n (Timedelta(10, unit="s"), "Timedelta('0 days 00:00:10')"),\n (Timedelta(10, unit="ms"), "Timedelta('0 days 00:00:00.010000')"),\n (Timedelta(-10, unit="ms"), "Timedelta('-1 days +23:59:59.990000')"),\n ],\n)\ndef test_repr(td, expected_repr):\n assert repr(td) == expected_repr\n\n\n@pytest.mark.parametrize(\n "td, expected_iso",\n [\n (\n Timedelta(\n days=6,\n minutes=50,\n seconds=3,\n milliseconds=10,\n microseconds=10,\n nanoseconds=12,\n ),\n "P6DT0H50M3.010010012S",\n ),\n (Timedelta(days=4, hours=12, minutes=30, seconds=5), "P4DT12H30M5S"),\n (Timedelta(nanoseconds=123), "P0DT0H0M0.000000123S"),\n # trim nano\n (Timedelta(microseconds=10), "P0DT0H0M0.00001S"),\n # trim micro\n (Timedelta(milliseconds=1), "P0DT0H0M0.001S"),\n # don't strip every 0\n (Timedelta(minutes=1), "P0DT0H1M0S"),\n ],\n)\ndef test_isoformat(td, expected_iso):\n assert td.isoformat() == expected_iso\n\n\nclass TestReprBase:\n def test_none(self):\n delta_1d = Timedelta(1, unit="D")\n delta_0d = Timedelta(0, unit="D")\n delta_1s = Timedelta(1, unit="s")\n delta_500ms = Timedelta(500, unit="ms")\n\n drepr = lambda x: x._repr_base()\n assert drepr(delta_1d) == "1 days"\n assert drepr(-delta_1d) == "-1 days"\n assert drepr(delta_0d) == "0 days"\n assert drepr(delta_1s) == "0 days 00:00:01"\n assert drepr(delta_500ms) == "0 days 00:00:00.500000"\n assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"\n assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"\n assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"\n assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"\n\n def test_sub_day(self):\n delta_1d = Timedelta(1, unit="D")\n delta_0d = Timedelta(0, unit="D")\n delta_1s = Timedelta(1, unit="s")\n delta_500ms = Timedelta(500, unit="ms")\n\n drepr = lambda x: x._repr_base(format="sub_day")\n assert drepr(delta_1d) == "1 days"\n assert drepr(-delta_1d) == "-1 days"\n assert drepr(delta_0d) == "00:00:00"\n assert drepr(delta_1s) == "00:00:01"\n assert drepr(delta_500ms) == "00:00:00.500000"\n assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"\n assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"\n assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"\n assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"\n\n def test_long(self):\n delta_1d = Timedelta(1, unit="D")\n delta_0d = Timedelta(0, unit="D")\n delta_1s = Timedelta(1, unit="s")\n delta_500ms = Timedelta(500, unit="ms")\n\n drepr = lambda x: x._repr_base(format="long")\n assert drepr(delta_1d) == "1 days 00:00:00"\n assert drepr(-delta_1d) == "-1 days +00:00:00"\n assert drepr(delta_0d) == "0 days 00:00:00"\n assert drepr(delta_1s) == "0 days 00:00:01"\n assert drepr(delta_500ms) == "0 days 00:00:00.500000"\n assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"\n assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"\n assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"\n assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"\n\n def test_all(self):\n delta_1d = Timedelta(1, unit="D")\n delta_0d = Timedelta(0, unit="D")\n delta_1ns = Timedelta(1, unit="ns")\n\n drepr = lambda x: x._repr_base(format="all")\n assert drepr(delta_1d) == "1 days 00:00:00.000000000"\n assert drepr(-delta_1d) == "-1 days +00:00:00.000000000"\n assert drepr(delta_0d) == "0 days 00:00:00.000000000"\n assert drepr(delta_1ns) == "0 days 00:00:00.000000001"\n assert drepr(-delta_1d + delta_1ns) == "-1 days +00:00:00.000000001"\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\test_formats.py
test_formats.py
Python
4,161
0.95
0.06422
0.031579
react-lib
499
2023-09-28T12:18:34.047836
MIT
true
0ca3ba990d1b52459d5d5240ad4a7f79
""" test the scalar Timedelta """\nfrom datetime import timedelta\nimport sys\n\nfrom hypothesis import (\n given,\n strategies as st,\n)\nimport numpy as np\nimport pytest\n\nfrom pandas._libs import lib\nfrom pandas._libs.tslibs import (\n NaT,\n iNaT,\n)\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas.errors import OutOfBoundsTimedelta\n\nfrom pandas import (\n Timedelta,\n to_timedelta,\n)\nimport pandas._testing as tm\n\n\nclass TestNonNano:\n @pytest.fixture(params=["s", "ms", "us"])\n def unit_str(self, request):\n return request.param\n\n @pytest.fixture\n def unit(self, unit_str):\n # 7, 8, 9 correspond to second, millisecond, and microsecond, respectively\n attr = f"NPY_FR_{unit_str}"\n return getattr(NpyDatetimeUnit, attr).value\n\n @pytest.fixture\n def val(self, unit):\n # microsecond that would be just out of bounds for nano\n us = 9223372800000000\n if unit == NpyDatetimeUnit.NPY_FR_us.value:\n value = us\n elif unit == NpyDatetimeUnit.NPY_FR_ms.value:\n value = us // 1000\n else:\n value = us // 1_000_000\n return value\n\n @pytest.fixture\n def td(self, unit, val):\n return Timedelta._from_value_and_reso(val, unit)\n\n def test_from_value_and_reso(self, unit, val):\n # Just checking that the fixture is giving us what we asked for\n td = Timedelta._from_value_and_reso(val, unit)\n assert td._value == val\n assert td._creso == unit\n assert td.days == 106752\n\n def test_unary_non_nano(self, td, unit):\n assert abs(td)._creso == unit\n assert (-td)._creso == unit\n assert (+td)._creso == unit\n\n def test_sub_preserves_reso(self, td, unit):\n res = td - td\n expected = Timedelta._from_value_and_reso(0, unit)\n assert res == expected\n assert res._creso == unit\n\n def test_mul_preserves_reso(self, td, unit):\n # The td fixture should always be far from the implementation\n # bound, so doubling does not risk overflow.\n res = td * 2\n assert res._value == td._value * 2\n assert res._creso == unit\n\n def test_cmp_cross_reso(self, td):\n # numpy gets this wrong because of silent overflow\n other = Timedelta(days=106751, unit="ns")\n assert other < td\n assert td > other\n assert not other == td\n assert td != other\n\n def test_to_pytimedelta(self, td):\n res = td.to_pytimedelta()\n expected = timedelta(days=106752)\n assert type(res) is timedelta\n assert res == expected\n\n def test_to_timedelta64(self, td, unit):\n for res in [td.to_timedelta64(), td.to_numpy(), td.asm8]:\n assert isinstance(res, np.timedelta64)\n assert res.view("i8") == td._value\n if unit == NpyDatetimeUnit.NPY_FR_s.value:\n assert res.dtype == "m8[s]"\n elif unit == NpyDatetimeUnit.NPY_FR_ms.value:\n assert res.dtype == "m8[ms]"\n elif unit == NpyDatetimeUnit.NPY_FR_us.value:\n assert res.dtype == "m8[us]"\n\n def test_truediv_timedeltalike(self, td):\n assert td / td == 1\n assert (2.5 * td) / td == 2.5\n\n other = Timedelta(td._value)\n msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow."\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td / other\n\n # Timedelta(other.to_pytimedelta()) has microsecond resolution,\n # so the division doesn't require casting all the way to nanos,\n # so succeeds\n res = other.to_pytimedelta() / td\n expected = other.to_pytimedelta() / td.to_pytimedelta()\n assert res == expected\n\n # if there's no overflow, we cast to the higher reso\n left = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_us.value)\n right = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_ms.value)\n result = left / right\n assert result == 0.001\n\n result = right / left\n assert result == 1000\n\n def test_truediv_numeric(self, td):\n assert td / np.nan is NaT\n\n res = td / 2\n assert res._value == td._value / 2\n assert res._creso == td._creso\n\n res = td / 2.0\n assert res._value == td._value / 2\n assert res._creso == td._creso\n\n def test_floordiv_timedeltalike(self, td):\n assert td // td == 1\n assert (2.5 * td) // td == 2\n\n other = Timedelta(td._value)\n msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td // other\n\n # Timedelta(other.to_pytimedelta()) has microsecond resolution,\n # so the floordiv doesn't require casting all the way to nanos,\n # so succeeds\n res = other.to_pytimedelta() // td\n assert res == 0\n\n # if there's no overflow, we cast to the higher reso\n left = Timedelta._from_value_and_reso(50050, NpyDatetimeUnit.NPY_FR_us.value)\n right = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_ms.value)\n result = left // right\n assert result == 1\n result = right // left\n assert result == 0\n\n def test_floordiv_numeric(self, td):\n assert td // np.nan is NaT\n\n res = td // 2\n assert res._value == td._value // 2\n assert res._creso == td._creso\n\n res = td // 2.0\n assert res._value == td._value // 2\n assert res._creso == td._creso\n\n assert td // np.array(np.nan) is NaT\n\n res = td // np.array(2)\n assert res._value == td._value // 2\n assert res._creso == td._creso\n\n res = td // np.array(2.0)\n assert res._value == td._value // 2\n assert res._creso == td._creso\n\n def test_addsub_mismatched_reso(self, td):\n # need to cast to since td is out of bounds for ns, so\n # so we would raise OverflowError without casting\n other = Timedelta(days=1).as_unit("us")\n\n # td is out of bounds for ns\n result = td + other\n assert result._creso == other._creso\n assert result.days == td.days + 1\n\n result = other + td\n assert result._creso == other._creso\n assert result.days == td.days + 1\n\n result = td - other\n assert result._creso == other._creso\n assert result.days == td.days - 1\n\n result = other - td\n assert result._creso == other._creso\n assert result.days == 1 - td.days\n\n other2 = Timedelta(500)\n msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td + other2\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n other2 + td\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td - other2\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n other2 - td\n\n def test_min(self, td):\n assert td.min <= td\n assert td.min._creso == td._creso\n assert td.min._value == NaT._value + 1\n\n def test_max(self, td):\n assert td.max >= td\n assert td.max._creso == td._creso\n assert td.max._value == np.iinfo(np.int64).max\n\n def test_resolution(self, td):\n expected = Timedelta._from_value_and_reso(1, td._creso)\n result = td.resolution\n assert result == expected\n assert result._creso == expected._creso\n\n def test_hash(self) -> None:\n # GH#54037\n second_resolution_max = Timedelta(0).as_unit("s").max\n\n assert hash(second_resolution_max)\n\n\ndef test_timedelta_class_min_max_resolution():\n # when accessed on the class (as opposed to an instance), we default\n # to nanoseconds\n assert Timedelta.min == Timedelta(NaT._value + 1)\n assert Timedelta.min._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n assert Timedelta.max == Timedelta(np.iinfo(np.int64).max)\n assert Timedelta.max._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n assert Timedelta.resolution == Timedelta(1)\n assert Timedelta.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n\nclass TestTimedeltaUnaryOps:\n def test_invert(self):\n td = Timedelta(10, unit="d")\n\n msg = "bad operand type for unary ~"\n with pytest.raises(TypeError, match=msg):\n ~td\n\n # check this matches pytimedelta and timedelta64\n with pytest.raises(TypeError, match=msg):\n ~(td.to_pytimedelta())\n\n umsg = "ufunc 'invert' not supported for the input types"\n with pytest.raises(TypeError, match=umsg):\n ~(td.to_timedelta64())\n\n def test_unary_ops(self):\n td = Timedelta(10, unit="d")\n\n # __neg__, __pos__\n assert -td == Timedelta(-10, unit="d")\n assert -td == Timedelta("-10d")\n assert +td == Timedelta(10, unit="d")\n\n # __abs__, __abs__(__neg__)\n assert abs(td) == td\n assert abs(-td) == td\n assert abs(-td) == Timedelta("10d")\n\n\nclass TestTimedeltas:\n @pytest.mark.parametrize(\n "unit, value, expected",\n [\n ("us", 9.999, 9999),\n ("ms", 9.999999, 9999999),\n ("s", 9.999999999, 9999999999),\n ],\n )\n def test_rounding_on_int_unit_construction(self, unit, value, expected):\n # GH 12690\n result = Timedelta(value, unit=unit)\n assert result._value == expected\n result = Timedelta(str(value) + unit)\n assert result._value == expected\n\n def test_total_seconds_scalar(self):\n # see gh-10939\n rng = Timedelta("1 days, 10:11:12.100123456")\n expt = 1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9\n tm.assert_almost_equal(rng.total_seconds(), expt)\n\n rng = Timedelta(np.nan)\n assert np.isnan(rng.total_seconds())\n\n def test_conversion(self):\n for td in [Timedelta(10, unit="d"), Timedelta("1 days, 10:11:12.012345")]:\n pydt = td.to_pytimedelta()\n assert td == Timedelta(pydt)\n assert td == pydt\n assert isinstance(pydt, timedelta) and not isinstance(pydt, Timedelta)\n\n assert td == np.timedelta64(td._value, "ns")\n td64 = td.to_timedelta64()\n\n assert td64 == np.timedelta64(td._value, "ns")\n assert td == td64\n\n assert isinstance(td64, np.timedelta64)\n\n # this is NOT equal and cannot be roundtripped (because of the nanos)\n td = Timedelta("1 days, 10:11:12.012345678")\n assert td != td.to_pytimedelta()\n\n def test_fields(self):\n def check(value):\n # that we are int\n assert isinstance(value, int)\n\n # compat to datetime.timedelta\n rng = to_timedelta("1 days, 10:11:12")\n assert rng.days == 1\n assert rng.seconds == 10 * 3600 + 11 * 60 + 12\n assert rng.microseconds == 0\n assert rng.nanoseconds == 0\n\n msg = "'Timedelta' object has no attribute '{}'"\n with pytest.raises(AttributeError, match=msg.format("hours")):\n rng.hours\n with pytest.raises(AttributeError, match=msg.format("minutes")):\n rng.minutes\n with pytest.raises(AttributeError, match=msg.format("milliseconds")):\n rng.milliseconds\n\n # GH 10050\n check(rng.days)\n check(rng.seconds)\n check(rng.microseconds)\n check(rng.nanoseconds)\n\n td = Timedelta("-1 days, 10:11:12")\n assert abs(td) == Timedelta("13:48:48")\n assert str(td) == "-1 days +10:11:12"\n assert -td == Timedelta("0 days 13:48:48")\n assert -Timedelta("-1 days, 10:11:12")._value == 49728000000000\n assert Timedelta("-1 days, 10:11:12")._value == -49728000000000\n\n rng = to_timedelta("-1 days, 10:11:12.100123456")\n assert rng.days == -1\n assert rng.seconds == 10 * 3600 + 11 * 60 + 12\n assert rng.microseconds == 100 * 1000 + 123\n assert rng.nanoseconds == 456\n msg = "'Timedelta' object has no attribute '{}'"\n with pytest.raises(AttributeError, match=msg.format("hours")):\n rng.hours\n with pytest.raises(AttributeError, match=msg.format("minutes")):\n rng.minutes\n with pytest.raises(AttributeError, match=msg.format("milliseconds")):\n rng.milliseconds\n\n # components\n tup = to_timedelta(-1, "us").components\n assert tup.days == -1\n assert tup.hours == 23\n assert tup.minutes == 59\n assert tup.seconds == 59\n assert tup.milliseconds == 999\n assert tup.microseconds == 999\n assert tup.nanoseconds == 0\n\n # GH 10050\n check(tup.days)\n check(tup.hours)\n check(tup.minutes)\n check(tup.seconds)\n check(tup.milliseconds)\n check(tup.microseconds)\n check(tup.nanoseconds)\n\n tup = Timedelta("-1 days 1 us").components\n assert tup.days == -2\n assert tup.hours == 23\n assert tup.minutes == 59\n assert tup.seconds == 59\n assert tup.milliseconds == 999\n assert tup.microseconds == 999\n assert tup.nanoseconds == 0\n\n # TODO: this is a test of to_timedelta string parsing\n def test_iso_conversion(self):\n # GH #21877\n expected = Timedelta(1, unit="s")\n assert to_timedelta("P0DT0H0M1S") == expected\n\n # TODO: this is a test of to_timedelta returning NaT\n def test_nat_converters(self):\n result = to_timedelta("nat").to_numpy()\n assert result.dtype.kind == "M"\n assert result.astype("int64") == iNaT\n\n result = to_timedelta("nan").to_numpy()\n assert result.dtype.kind == "M"\n assert result.astype("int64") == iNaT\n\n def test_numeric_conversions(self):\n assert Timedelta(0) == np.timedelta64(0, "ns")\n assert Timedelta(10) == np.timedelta64(10, "ns")\n assert Timedelta(10, unit="ns") == np.timedelta64(10, "ns")\n\n assert Timedelta(10, unit="us") == np.timedelta64(10, "us")\n assert Timedelta(10, unit="ms") == np.timedelta64(10, "ms")\n assert Timedelta(10, unit="s") == np.timedelta64(10, "s")\n assert Timedelta(10, unit="d") == np.timedelta64(10, "D")\n\n def test_timedelta_conversions(self):\n assert Timedelta(timedelta(seconds=1)) == np.timedelta64(1, "s").astype(\n "m8[ns]"\n )\n assert Timedelta(timedelta(microseconds=1)) == np.timedelta64(1, "us").astype(\n "m8[ns]"\n )\n assert Timedelta(timedelta(days=1)) == np.timedelta64(1, "D").astype("m8[ns]")\n\n def test_to_numpy_alias(self):\n # GH 24653: alias .to_numpy() for scalars\n td = Timedelta("10m7s")\n assert td.to_timedelta64() == td.to_numpy()\n\n # GH#44460\n msg = "dtype and copy arguments are ignored"\n with pytest.raises(ValueError, match=msg):\n td.to_numpy("m8[s]")\n with pytest.raises(ValueError, match=msg):\n td.to_numpy(copy=True)\n\n def test_identity(self):\n td = Timedelta(10, unit="d")\n assert isinstance(td, Timedelta)\n assert isinstance(td, timedelta)\n\n def test_short_format_converters(self):\n def conv(v):\n return v.astype("m8[ns]")\n\n assert Timedelta("10") == np.timedelta64(10, "ns")\n assert Timedelta("10ns") == np.timedelta64(10, "ns")\n assert Timedelta("100") == np.timedelta64(100, "ns")\n assert Timedelta("100ns") == np.timedelta64(100, "ns")\n\n assert Timedelta("1000") == np.timedelta64(1000, "ns")\n assert Timedelta("1000ns") == np.timedelta64(1000, "ns")\n assert Timedelta("1000NS") == np.timedelta64(1000, "ns")\n\n assert Timedelta("10us") == np.timedelta64(10000, "ns")\n assert Timedelta("100us") == np.timedelta64(100000, "ns")\n assert Timedelta("1000us") == np.timedelta64(1000000, "ns")\n assert Timedelta("1000Us") == np.timedelta64(1000000, "ns")\n assert Timedelta("1000uS") == np.timedelta64(1000000, "ns")\n\n assert Timedelta("1ms") == np.timedelta64(1000000, "ns")\n assert Timedelta("10ms") == np.timedelta64(10000000, "ns")\n assert Timedelta("100ms") == np.timedelta64(100000000, "ns")\n assert Timedelta("1000ms") == np.timedelta64(1000000000, "ns")\n\n assert Timedelta("-1s") == -np.timedelta64(1000000000, "ns")\n assert Timedelta("1s") == np.timedelta64(1000000000, "ns")\n assert Timedelta("10s") == np.timedelta64(10000000000, "ns")\n assert Timedelta("100s") == np.timedelta64(100000000000, "ns")\n assert Timedelta("1000s") == np.timedelta64(1000000000000, "ns")\n\n assert Timedelta("1d") == conv(np.timedelta64(1, "D"))\n assert Timedelta("-1d") == -conv(np.timedelta64(1, "D"))\n assert Timedelta("1D") == conv(np.timedelta64(1, "D"))\n assert Timedelta("10D") == conv(np.timedelta64(10, "D"))\n assert Timedelta("100D") == conv(np.timedelta64(100, "D"))\n assert Timedelta("1000D") == conv(np.timedelta64(1000, "D"))\n assert Timedelta("10000D") == conv(np.timedelta64(10000, "D"))\n\n # space\n assert Timedelta(" 10000D ") == conv(np.timedelta64(10000, "D"))\n assert Timedelta(" - 10000D ") == -conv(np.timedelta64(10000, "D"))\n\n # invalid\n msg = "invalid unit abbreviation"\n with pytest.raises(ValueError, match=msg):\n Timedelta("1foo")\n msg = "unit abbreviation w/o a number"\n with pytest.raises(ValueError, match=msg):\n Timedelta("foo")\n\n def test_full_format_converters(self):\n def conv(v):\n return v.astype("m8[ns]")\n\n d1 = np.timedelta64(1, "D")\n\n assert Timedelta("1days") == conv(d1)\n assert Timedelta("1days,") == conv(d1)\n assert Timedelta("- 1days,") == -conv(d1)\n\n assert Timedelta("00:00:01") == conv(np.timedelta64(1, "s"))\n assert Timedelta("06:00:01") == conv(np.timedelta64(6 * 3600 + 1, "s"))\n assert Timedelta("06:00:01.0") == conv(np.timedelta64(6 * 3600 + 1, "s"))\n assert Timedelta("06:00:01.01") == conv(\n np.timedelta64(1000 * (6 * 3600 + 1) + 10, "ms")\n )\n\n assert Timedelta("- 1days, 00:00:01") == conv(-d1 + np.timedelta64(1, "s"))\n assert Timedelta("1days, 06:00:01") == conv(\n d1 + np.timedelta64(6 * 3600 + 1, "s")\n )\n assert Timedelta("1days, 06:00:01.01") == conv(\n d1 + np.timedelta64(1000 * (6 * 3600 + 1) + 10, "ms")\n )\n\n # invalid\n msg = "have leftover units"\n with pytest.raises(ValueError, match=msg):\n Timedelta("- 1days, 00")\n\n def test_pickle(self):\n v = Timedelta("1 days 10:11:12.0123456")\n v_p = tm.round_trip_pickle(v)\n assert v == v_p\n\n def test_timedelta_hash_equality(self):\n # GH 11129\n v = Timedelta(1, "D")\n td = timedelta(days=1)\n assert hash(v) == hash(td)\n\n d = {td: 2}\n assert d[v] == 2\n\n tds = [Timedelta(seconds=1) + Timedelta(days=n) for n in range(20)]\n assert all(hash(td) == hash(td.to_pytimedelta()) for td in tds)\n\n # python timedeltas drop ns resolution\n ns_td = Timedelta(1, "ns")\n assert hash(ns_td) != hash(ns_td.to_pytimedelta())\n\n @pytest.mark.skip_ubsan\n @pytest.mark.xfail(\n reason="pd.Timedelta violates the Python hash invariant (GH#44504).",\n )\n @given(\n st.integers(\n min_value=(-sys.maxsize - 1) // 500,\n max_value=sys.maxsize // 500,\n )\n )\n def test_hash_equality_invariance(self, half_microseconds: int) -> None:\n # GH#44504\n\n nanoseconds = half_microseconds * 500\n\n pandas_timedelta = Timedelta(nanoseconds)\n numpy_timedelta = np.timedelta64(nanoseconds)\n\n # See: https://docs.python.org/3/glossary.html#term-hashable\n # Hashable objects which compare equal must have the same hash value.\n assert pandas_timedelta != numpy_timedelta or hash(pandas_timedelta) == hash(\n numpy_timedelta\n )\n\n def test_implementation_limits(self):\n min_td = Timedelta(Timedelta.min)\n max_td = Timedelta(Timedelta.max)\n\n # GH 12727\n # timedelta limits correspond to int64 boundaries\n assert min_td._value == iNaT + 1\n assert max_td._value == lib.i8max\n\n # Beyond lower limit, a NAT before the Overflow\n assert (min_td - Timedelta(1, "ns")) is NaT\n\n msg = "int too (large|big) to convert"\n with pytest.raises(OverflowError, match=msg):\n min_td - Timedelta(2, "ns")\n\n with pytest.raises(OverflowError, match=msg):\n max_td + Timedelta(1, "ns")\n\n # Same tests using the internal nanosecond values\n td = Timedelta(min_td._value - 1, "ns")\n assert td is NaT\n\n msg = "Cannot cast -9223372036854775809 from ns to 'ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(min_td._value - 2, "ns")\n\n msg = "Cannot cast 9223372036854775808 from ns to 'ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta(max_td._value + 1, "ns")\n\n def test_total_seconds_precision(self):\n # GH 19458\n assert Timedelta("30s").total_seconds() == 30.0\n assert Timedelta("0").total_seconds() == 0.0\n assert Timedelta("-2s").total_seconds() == -2.0\n assert Timedelta("5.324s").total_seconds() == 5.324\n assert (Timedelta("30s").total_seconds() - 30.0) < 1e-20\n assert (30.0 - Timedelta("30s").total_seconds()) < 1e-20\n\n def test_resolution_string(self):\n assert Timedelta(days=1).resolution_string == "D"\n assert Timedelta(days=1, hours=6).resolution_string == "h"\n assert Timedelta(days=1, minutes=6).resolution_string == "min"\n assert Timedelta(days=1, seconds=6).resolution_string == "s"\n assert Timedelta(days=1, milliseconds=6).resolution_string == "ms"\n assert Timedelta(days=1, microseconds=6).resolution_string == "us"\n assert Timedelta(days=1, nanoseconds=6).resolution_string == "ns"\n\n def test_resolution_deprecated(self):\n # GH#21344\n td = Timedelta(days=4, hours=3)\n result = td.resolution\n assert result == Timedelta(nanoseconds=1)\n\n # Check that the attribute is available on the class, mirroring\n # the stdlib timedelta behavior\n result = Timedelta.resolution\n assert result == Timedelta(nanoseconds=1)\n\n\n@pytest.mark.parametrize(\n "value, expected",\n [\n (Timedelta("10s"), True),\n (Timedelta("-10s"), True),\n (Timedelta(10, unit="ns"), True),\n (Timedelta(0, unit="ns"), False),\n (Timedelta(-10, unit="ns"), True),\n (Timedelta(None), True),\n (NaT, True),\n ],\n)\ndef test_truthiness(value, expected):\n # https://github.com/pandas-dev/pandas/issues/21484\n assert bool(value) is expected\n\n\ndef test_timedelta_attribute_precision():\n # GH 31354\n td = Timedelta(1552211999999999872, unit="ns")\n result = td.days * 86400\n result += td.seconds\n result *= 1000000\n result += td.microseconds\n result *= 1000\n result += td.nanoseconds\n expected = td._value\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\test_timedelta.py
test_timedelta.py
Python
23,413
0.95
0.100601
0.099448
python-kit
879
2024-12-09T09:59:42.420777
GPL-3.0
true
1b5adb79f1b9de5fd56416e0a42a9052
import pytest\n\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas.errors import OutOfBoundsTimedelta\n\nfrom pandas import Timedelta\n\n\nclass TestAsUnit:\n def test_as_unit(self):\n td = Timedelta(days=1)\n\n assert td.as_unit("ns") is td\n\n res = td.as_unit("us")\n assert res._value == td._value // 1000\n assert res._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n rt = res.as_unit("ns")\n assert rt._value == td._value\n assert rt._creso == td._creso\n\n res = td.as_unit("ms")\n assert res._value == td._value // 1_000_000\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n rt = res.as_unit("ns")\n assert rt._value == td._value\n assert rt._creso == td._creso\n\n res = td.as_unit("s")\n assert res._value == td._value // 1_000_000_000\n assert res._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n rt = res.as_unit("ns")\n assert rt._value == td._value\n assert rt._creso == td._creso\n\n def test_as_unit_overflows(self):\n # microsecond that would be just out of bounds for nano\n us = 9223372800000000\n td = Timedelta._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value)\n\n msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n td.as_unit("ns")\n\n res = td.as_unit("ms")\n assert res._value == us // 1000\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n def test_as_unit_rounding(self):\n td = Timedelta(microseconds=1500)\n res = td.as_unit("ms")\n\n expected = Timedelta(milliseconds=1)\n assert res == expected\n\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n assert res._value == 1\n\n with pytest.raises(ValueError, match="Cannot losslessly convert units"):\n td.as_unit("ms", round_ok=False)\n\n def test_as_unit_non_nano(self):\n # case where we are going neither to nor from nano\n td = Timedelta(days=1).as_unit("ms")\n assert td.days == 1\n assert td._value == 86_400_000\n assert td.components.days == 1\n assert td._d == 1\n assert td.total_seconds() == 86400\n\n res = td.as_unit("us")\n assert res._value == 86_400_000_000\n assert res.components.days == 1\n assert res.components.hours == 0\n assert res._d == 1\n assert res._h == 0\n assert res.total_seconds() == 86400\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\methods\test_as_unit.py
test_as_unit.py
Python
2,518
0.95
0.075
0.033333
react-lib
201
2025-04-01T17:58:30.240990
MIT
true
31c4174c138a76613745de9563b50273
from hypothesis import (\n given,\n strategies as st,\n)\nimport numpy as np\nimport pytest\n\nfrom pandas._libs import lib\nfrom pandas._libs.tslibs import iNaT\nfrom pandas.errors import OutOfBoundsTimedelta\n\nfrom pandas import Timedelta\n\n\nclass TestTimedeltaRound:\n @pytest.mark.parametrize(\n "freq,s1,s2",\n [\n # This first case has s1, s2 being the same as t1,t2 below\n (\n "ns",\n Timedelta("1 days 02:34:56.789123456"),\n Timedelta("-1 days 02:34:56.789123456"),\n ),\n (\n "us",\n Timedelta("1 days 02:34:56.789123000"),\n Timedelta("-1 days 02:34:56.789123000"),\n ),\n (\n "ms",\n Timedelta("1 days 02:34:56.789000000"),\n Timedelta("-1 days 02:34:56.789000000"),\n ),\n ("s", Timedelta("1 days 02:34:57"), Timedelta("-1 days 02:34:57")),\n ("2s", Timedelta("1 days 02:34:56"), Timedelta("-1 days 02:34:56")),\n ("5s", Timedelta("1 days 02:34:55"), Timedelta("-1 days 02:34:55")),\n ("min", Timedelta("1 days 02:35:00"), Timedelta("-1 days 02:35:00")),\n ("12min", Timedelta("1 days 02:36:00"), Timedelta("-1 days 02:36:00")),\n ("h", Timedelta("1 days 03:00:00"), Timedelta("-1 days 03:00:00")),\n ("d", Timedelta("1 days"), Timedelta("-1 days")),\n ],\n )\n def test_round(self, freq, s1, s2):\n t1 = Timedelta("1 days 02:34:56.789123456")\n t2 = Timedelta("-1 days 02:34:56.789123456")\n\n r1 = t1.round(freq)\n assert r1 == s1\n r2 = t2.round(freq)\n assert r2 == s2\n\n def test_round_invalid(self):\n t1 = Timedelta("1 days 02:34:56.789123456")\n\n for freq, msg in [\n ("YE", "<YearEnd: month=12> is a non-fixed frequency"),\n ("ME", "<MonthEnd> is a non-fixed frequency"),\n ("foobar", "Invalid frequency: foobar"),\n ]:\n with pytest.raises(ValueError, match=msg):\n t1.round(freq)\n\n @pytest.mark.skip_ubsan\n def test_round_implementation_bounds(self):\n # See also: analogous test for Timestamp\n # GH#38964\n result = Timedelta.min.ceil("s")\n expected = Timedelta.min + Timedelta(seconds=1) - Timedelta(145224193)\n assert result == expected\n\n result = Timedelta.max.floor("s")\n expected = Timedelta.max - Timedelta(854775807)\n assert result == expected\n\n msg = (\n r"Cannot round -106752 days \+00:12:43.145224193 to freq=s without overflow"\n )\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta.min.floor("s")\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta.min.round("s")\n\n msg = "Cannot round 106751 days 23:47:16.854775807 to freq=s without overflow"\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta.max.ceil("s")\n with pytest.raises(OutOfBoundsTimedelta, match=msg):\n Timedelta.max.round("s")\n\n @pytest.mark.skip_ubsan\n @given(val=st.integers(min_value=iNaT + 1, max_value=lib.i8max))\n @pytest.mark.parametrize(\n "method", [Timedelta.round, Timedelta.floor, Timedelta.ceil]\n )\n def test_round_sanity(self, val, method):\n cls = Timedelta\n err_cls = OutOfBoundsTimedelta\n\n val = np.int64(val)\n td = cls(val)\n\n def checker(ts, nanos, unit):\n # First check that we do raise in cases where we should\n if nanos == 1:\n pass\n else:\n div, mod = divmod(ts._value, nanos)\n diff = int(nanos - mod)\n lb = ts._value - mod\n assert lb <= ts._value # i.e. no overflows with python ints\n ub = ts._value + diff\n assert ub > ts._value # i.e. no overflows with python ints\n\n msg = "without overflow"\n if mod == 0:\n # We should never be raising in this\n pass\n elif method is cls.ceil:\n if ub > cls.max._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif method is cls.floor:\n if lb < cls.min._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif mod >= diff:\n if ub > cls.max._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif lb < cls.min._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n\n res = method(ts, unit)\n\n td = res - ts\n diff = abs(td._value)\n assert diff < nanos\n assert res._value % nanos == 0\n\n if method is cls.round:\n assert diff <= nanos / 2\n elif method is cls.floor:\n assert res <= ts\n elif method is cls.ceil:\n assert res >= ts\n\n nanos = 1\n checker(td, nanos, "ns")\n\n nanos = 1000\n checker(td, nanos, "us")\n\n nanos = 1_000_000\n checker(td, nanos, "ms")\n\n nanos = 1_000_000_000\n checker(td, nanos, "s")\n\n nanos = 60 * 1_000_000_000\n checker(td, nanos, "min")\n\n nanos = 60 * 60 * 1_000_000_000\n checker(td, nanos, "h")\n\n nanos = 24 * 60 * 60 * 1_000_000_000\n checker(td, nanos, "D")\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_round_non_nano(self, unit):\n td = Timedelta("1 days 02:34:57").as_unit(unit)\n\n res = td.round("min")\n assert res == Timedelta("1 days 02:35:00")\n assert res._creso == td._creso\n\n res = td.floor("min")\n assert res == Timedelta("1 days 02:34:00")\n assert res._creso == td._creso\n\n res = td.ceil("min")\n assert res == Timedelta("1 days 02:35:00")\n assert res._creso == td._creso\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\methods\test_round.py
test_round.py
Python
6,338
0.95
0.080214
0.031646
awesome-app
142
2024-11-16T18:13:10.442673
BSD-3-Clause
true
e7004e58d8f2a5b09fb8817ef18f1494
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\methods\__pycache__\test_as_unit.cpython-313.pyc
test_as_unit.cpython-313.pyc
Other
5,134
0.8
0
0
awesome-app
69
2025-05-20T16:05:59.583201
BSD-3-Clause
true
8e8a124a68d5194f2db6f705407695a3
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\methods\__pycache__\test_round.cpython-313.pyc
test_round.cpython-313.pyc
Other
8,983
0.8
0
0
react-lib
730
2023-07-24T08:30:03.977143
GPL-3.0
true
fe9ccf9c8c2df31fd06c36988228d5b9
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\methods\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
212
0.7
0
0
node-utils
942
2023-08-08T13:29:57.744701
MIT
true
d14238cae29110b9502c3afd86061320
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
64,570
0.75
0.029654
0.021997
python-kit
761
2023-08-18T07:46:55.590235
GPL-3.0
true
bf2db24ba5e8d6cf8d9cac36ea38e74e
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
30,793
0.95
0.003049
0.003115
vue-tools
638
2024-10-11T12:40:43.948261
BSD-3-Clause
true
b64a3c684a44cfaa230ed44339661c74
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
5,964
0.8
0
0
python-kit
312
2024-01-15T02:03:20.760726
Apache-2.0
true
fe24e7f90c214cd588473f8892ecaa53
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\__pycache__\test_timedelta.cpython-313.pyc
test_timedelta.cpython-313.pyc
Other
39,896
0.8
0.006173
0.003135
node-utils
428
2025-04-27T00:22:29.562909
BSD-3-Clause
true
b442db1c472f52167e1432b50d49f04b
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timedelta\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
204
0.7
0
0
awesome-app
738
2023-08-19T00:02:17.123848
GPL-3.0
true
caf72e6b7227cc92203852cff9873db0
from datetime import (\n datetime,\n timedelta,\n timezone,\n)\n\nfrom dateutil.tz import gettz\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import (\n OutOfBoundsDatetime,\n OutOfBoundsTimedelta,\n Timedelta,\n Timestamp,\n offsets,\n to_offset,\n)\n\nimport pandas._testing as tm\n\n\nclass TestTimestampArithmetic:\n def test_overflow_offset(self):\n # no overflow expected\n\n stamp = Timestamp("2000/1/1")\n offset_no_overflow = to_offset("D") * 100\n\n expected = Timestamp("2000/04/10")\n assert stamp + offset_no_overflow == expected\n\n assert offset_no_overflow + stamp == expected\n\n expected = Timestamp("1999/09/23")\n assert stamp - offset_no_overflow == expected\n\n def test_overflow_offset_raises(self):\n # xref https://github.com/statsmodels/statsmodels/issues/3374\n # ends up multiplying really large numbers which overflow\n\n stamp = Timestamp("2017-01-13 00:00:00").as_unit("ns")\n offset_overflow = 20169940 * offsets.Day(1)\n lmsg2 = r"Cannot cast -?20169940 days \+?00:00:00 to unit='ns' without overflow"\n\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):\n stamp + offset_overflow\n\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):\n offset_overflow + stamp\n\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):\n stamp - offset_overflow\n\n # xref https://github.com/pandas-dev/pandas/issues/14080\n # used to crash, so check for proper overflow exception\n\n stamp = Timestamp("2000/1/1").as_unit("ns")\n offset_overflow = to_offset("D") * 100**5\n\n lmsg3 = (\n r"Cannot cast -?10000000000 days \+?00:00:00 to unit='ns' without overflow"\n )\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):\n stamp + offset_overflow\n\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):\n offset_overflow + stamp\n\n with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):\n stamp - offset_overflow\n\n def test_overflow_timestamp_raises(self):\n # https://github.com/pandas-dev/pandas/issues/31774\n msg = "Result is too large"\n a = Timestamp("2101-01-01 00:00:00").as_unit("ns")\n b = Timestamp("1688-01-01 00:00:00").as_unit("ns")\n\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n a - b\n\n # but we're OK for timestamp and datetime.datetime\n assert (a - b.to_pydatetime()) == (a.to_pydatetime() - b)\n\n def test_delta_preserve_nanos(self):\n val = Timestamp(1337299200000000123)\n result = val + timedelta(1)\n assert result.nanosecond == val.nanosecond\n\n def test_rsub_dtscalars(self, tz_naive_fixture):\n # In particular, check that datetime64 - Timestamp works GH#28286\n td = Timedelta(1235345642000)\n ts = Timestamp("2021-01-01", tz=tz_naive_fixture)\n other = ts + td\n\n assert other - ts == td\n assert other.to_pydatetime() - ts == td\n if tz_naive_fixture is None:\n assert other.to_datetime64() - ts == td\n else:\n msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"\n with pytest.raises(TypeError, match=msg):\n other.to_datetime64() - ts\n\n def test_timestamp_sub_datetime(self):\n dt = datetime(2013, 10, 12)\n ts = Timestamp(datetime(2013, 10, 13))\n assert (ts - dt).days == 1\n assert (dt - ts).days == -1\n\n def test_subtract_tzaware_datetime(self):\n t1 = Timestamp("2020-10-22T22:00:00+00:00")\n t2 = datetime(2020, 10, 22, 22, tzinfo=timezone.utc)\n\n result = t1 - t2\n\n assert isinstance(result, Timedelta)\n assert result == Timedelta("0 days")\n\n def test_subtract_timestamp_from_different_timezone(self):\n t1 = Timestamp("20130101").tz_localize("US/Eastern")\n t2 = Timestamp("20130101").tz_localize("CET")\n\n result = t1 - t2\n\n assert isinstance(result, Timedelta)\n assert result == Timedelta("0 days 06:00:00")\n\n def test_subtracting_involving_datetime_with_different_tz(self):\n t1 = datetime(2013, 1, 1, tzinfo=timezone(timedelta(hours=-5)))\n t2 = Timestamp("20130101").tz_localize("CET")\n\n result = t1 - t2\n\n assert isinstance(result, Timedelta)\n assert result == Timedelta("0 days 06:00:00")\n\n result = t2 - t1\n assert isinstance(result, Timedelta)\n assert result == Timedelta("-1 days +18:00:00")\n\n def test_subtracting_different_timezones(self, tz_aware_fixture):\n t_raw = Timestamp("20130101")\n t_UTC = t_raw.tz_localize("UTC")\n t_diff = t_UTC.tz_convert(tz_aware_fixture) + Timedelta("0 days 05:00:00")\n\n result = t_diff - t_UTC\n\n assert isinstance(result, Timedelta)\n assert result == Timedelta("0 days 05:00:00")\n\n def test_addition_subtraction_types(self):\n # Assert on the types resulting from Timestamp +/- various date/time\n # objects\n dt = datetime(2014, 3, 4)\n td = timedelta(seconds=1)\n ts = Timestamp(dt)\n\n msg = "Addition/subtraction of integers"\n with pytest.raises(TypeError, match=msg):\n # GH#22535 add/sub with integers is deprecated\n ts + 1\n with pytest.raises(TypeError, match=msg):\n ts - 1\n\n # Timestamp + datetime not supported, though subtraction is supported\n # and yields timedelta more tests in tseries/base/tests/test_base.py\n assert type(ts - dt) == Timedelta\n assert type(ts + td) == Timestamp\n assert type(ts - td) == Timestamp\n\n # Timestamp +/- datetime64 not supported, so not tested (could possibly\n # assert error raised?)\n td64 = np.timedelta64(1, "D")\n assert type(ts + td64) == Timestamp\n assert type(ts - td64) == Timestamp\n\n @pytest.mark.parametrize(\n "td", [Timedelta(hours=3), np.timedelta64(3, "h"), timedelta(hours=3)]\n )\n def test_radd_tdscalar(self, td, fixed_now_ts):\n # GH#24775 timedelta64+Timestamp should not raise\n ts = fixed_now_ts\n assert td + ts == ts + td\n\n @pytest.mark.parametrize(\n "other,expected_difference",\n [\n (np.timedelta64(-123, "ns"), -123),\n (np.timedelta64(1234567898, "ns"), 1234567898),\n (np.timedelta64(-123, "us"), -123000),\n (np.timedelta64(-123, "ms"), -123000000),\n ],\n )\n def test_timestamp_add_timedelta64_unit(self, other, expected_difference):\n now = datetime.now(timezone.utc)\n ts = Timestamp(now).as_unit("ns")\n result = ts + other\n valdiff = result._value - ts._value\n assert valdiff == expected_difference\n\n ts2 = Timestamp(now)\n assert ts2 + other == result\n\n @pytest.mark.parametrize(\n "ts",\n [\n Timestamp("1776-07-04"),\n Timestamp("1776-07-04", tz="UTC"),\n ],\n )\n @pytest.mark.parametrize(\n "other",\n [\n 1,\n np.int64(1),\n np.array([1, 2], dtype=np.int32),\n np.array([3, 4], dtype=np.uint64),\n ],\n )\n def test_add_int_with_freq(self, ts, other):\n msg = "Addition/subtraction of integers and integer-arrays"\n with pytest.raises(TypeError, match=msg):\n ts + other\n with pytest.raises(TypeError, match=msg):\n other + ts\n\n with pytest.raises(TypeError, match=msg):\n ts - other\n\n msg = "unsupported operand type"\n with pytest.raises(TypeError, match=msg):\n other - ts\n\n @pytest.mark.parametrize("shape", [(6,), (2, 3)])\n def test_addsub_m8ndarray(self, shape):\n # GH#33296\n ts = Timestamp("2020-04-04 15:45").as_unit("ns")\n other = np.arange(6).astype("m8[h]").reshape(shape)\n\n result = ts + other\n\n ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]\n expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)\n tm.assert_numpy_array_equal(result, expected)\n\n result = other + ts\n tm.assert_numpy_array_equal(result, expected)\n\n result = ts - other\n ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]\n expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)\n tm.assert_numpy_array_equal(result, expected)\n\n msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"\n with pytest.raises(TypeError, match=msg):\n other - ts\n\n @pytest.mark.parametrize("shape", [(6,), (2, 3)])\n def test_addsub_m8ndarray_tzaware(self, shape):\n # GH#33296\n ts = Timestamp("2020-04-04 15:45", tz="US/Pacific")\n\n other = np.arange(6).astype("m8[h]").reshape(shape)\n\n result = ts + other\n\n ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]\n expected = np.array(ex_stamps).reshape(shape)\n tm.assert_numpy_array_equal(result, expected)\n\n result = other + ts\n tm.assert_numpy_array_equal(result, expected)\n\n result = ts - other\n ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]\n expected = np.array(ex_stamps).reshape(shape)\n tm.assert_numpy_array_equal(result, expected)\n\n msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"\n with pytest.raises(TypeError, match=msg):\n other - ts\n\n def test_subtract_different_utc_objects(self, utc_fixture, utc_fixture2):\n # GH 32619\n dt = datetime(2021, 1, 1)\n ts1 = Timestamp(dt, tz=utc_fixture)\n ts2 = Timestamp(dt, tz=utc_fixture2)\n result = ts1 - ts2\n expected = Timedelta(0)\n assert result == expected\n\n @pytest.mark.parametrize(\n "tz",\n [\n pytz.timezone("US/Eastern"),\n gettz("US/Eastern"),\n "US/Eastern",\n "dateutil/US/Eastern",\n ],\n )\n def test_timestamp_add_timedelta_push_over_dst_boundary(self, tz):\n # GH#1389\n\n # 4 hours before DST transition\n stamp = Timestamp("3/10/2012 22:00", tz=tz)\n\n result = stamp + timedelta(hours=6)\n\n # spring forward, + "7" hours\n expected = Timestamp("3/11/2012 05:00", tz=tz)\n\n assert result == expected\n\n\nclass SubDatetime(datetime):\n pass\n\n\n@pytest.mark.parametrize(\n "lh,rh",\n [\n (SubDatetime(2000, 1, 1), Timedelta(hours=1)),\n (Timedelta(hours=1), SubDatetime(2000, 1, 1)),\n ],\n)\ndef test_dt_subclass_add_timedelta(lh, rh):\n # GH#25851\n # ensure that subclassed datetime works for\n # Timedelta operations\n result = lh + rh\n expected = SubDatetime(2000, 1, 1, 1)\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_arithmetic.py
test_arithmetic.py
Python
10,852
0.95
0.098802
0.09542
node-utils
681
2024-08-03T01:55:51.284235
BSD-3-Clause
true
a627d11c3a47a82d84010816f139653c
from datetime import (\n datetime,\n timedelta,\n)\nimport operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas import Timestamp\nimport pandas._testing as tm\n\n\nclass TestTimestampComparison:\n def test_compare_non_nano_dt64(self):\n # don't raise when converting dt64 to Timestamp in __richcmp__\n dt = np.datetime64("1066-10-14")\n ts = Timestamp(dt)\n\n assert dt == ts\n\n def test_comparison_dt64_ndarray(self):\n ts = Timestamp("2021-01-01")\n ts2 = Timestamp("2019-04-05")\n arr = np.array([[ts.asm8, ts2.asm8]], dtype="M8[ns]")\n\n result = ts == arr\n expected = np.array([[True, False]], dtype=bool)\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr == ts\n tm.assert_numpy_array_equal(result, expected)\n\n result = ts != arr\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = arr != ts\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = ts2 < arr\n tm.assert_numpy_array_equal(result, expected)\n\n result = arr < ts2\n tm.assert_numpy_array_equal(result, np.array([[False, False]], dtype=bool))\n\n result = ts2 <= arr\n tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))\n\n result = arr <= ts2\n tm.assert_numpy_array_equal(result, ~expected)\n\n result = ts >= arr\n tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))\n\n result = arr >= ts\n tm.assert_numpy_array_equal(result, np.array([[True, False]], dtype=bool))\n\n @pytest.mark.parametrize("reverse", [True, False])\n def test_comparison_dt64_ndarray_tzaware(self, reverse, comparison_op):\n ts = Timestamp("2021-01-01 00:00:00.00000", tz="UTC")\n arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]")\n\n left, right = ts, arr\n if reverse:\n left, right = arr, ts\n\n if comparison_op is operator.eq:\n expected = np.array([False, False], dtype=bool)\n result = comparison_op(left, right)\n tm.assert_numpy_array_equal(result, expected)\n elif comparison_op is operator.ne:\n expected = np.array([True, True], dtype=bool)\n result = comparison_op(left, right)\n tm.assert_numpy_array_equal(result, expected)\n else:\n msg = "Cannot compare tz-naive and tz-aware timestamps"\n with pytest.raises(TypeError, match=msg):\n comparison_op(left, right)\n\n def test_comparison_object_array(self):\n # GH#15183\n ts = Timestamp("2011-01-03 00:00:00-0500", tz="US/Eastern")\n other = Timestamp("2011-01-01 00:00:00-0500", tz="US/Eastern")\n naive = Timestamp("2011-01-01 00:00:00")\n\n arr = np.array([other, ts], dtype=object)\n res = arr == ts\n expected = np.array([False, True], dtype=bool)\n assert (res == expected).all()\n\n # 2D case\n arr = np.array([[other, ts], [ts, other]], dtype=object)\n res = arr != ts\n expected = np.array([[True, False], [False, True]], dtype=bool)\n assert res.shape == expected.shape\n assert (res == expected).all()\n\n # tzaware mismatch\n arr = np.array([naive], dtype=object)\n msg = "Cannot compare tz-naive and tz-aware timestamps"\n with pytest.raises(TypeError, match=msg):\n arr < ts\n\n def test_comparison(self):\n # 5-18-2012 00:00:00.000\n stamp = 1337299200000000000\n\n val = Timestamp(stamp)\n\n assert val == val\n assert not val != val\n assert not val < val\n assert val <= val\n assert not val > val\n assert val >= val\n\n other = datetime(2012, 5, 18)\n assert val == other\n assert not val != other\n assert not val < other\n assert val <= other\n assert not val > other\n assert val >= other\n\n other = Timestamp(stamp + 100)\n\n assert val != other\n assert val != other\n assert val < other\n assert val <= other\n assert other > val\n assert other >= val\n\n def test_compare_invalid(self):\n # GH#8058\n val = Timestamp("20130101 12:01:02")\n assert not val == "foo"\n assert not val == 10.0\n assert not val == 1\n assert not val == []\n assert not val == {"foo": 1}\n assert not val == np.float64(1)\n assert not val == np.int64(1)\n\n assert val != "foo"\n assert val != 10.0\n assert val != 1\n assert val != []\n assert val != {"foo": 1}\n assert val != np.float64(1)\n assert val != np.int64(1)\n\n @pytest.mark.parametrize("tz", [None, "US/Pacific"])\n def test_compare_date(self, tz):\n # GH#36131 comparing Timestamp with date object is deprecated\n ts = Timestamp("2021-01-01 00:00:00.00000", tz=tz)\n dt = ts.to_pydatetime().date()\n # in 2.0 we disallow comparing pydate objects with Timestamps,\n # following the stdlib datetime behavior.\n\n msg = "Cannot compare Timestamp with datetime.date"\n for left, right in [(ts, dt), (dt, ts)]:\n assert not left == right\n assert left != right\n\n with pytest.raises(TypeError, match=msg):\n left < right\n with pytest.raises(TypeError, match=msg):\n left <= right\n with pytest.raises(TypeError, match=msg):\n left > right\n with pytest.raises(TypeError, match=msg):\n left >= right\n\n def test_cant_compare_tz_naive_w_aware(self, utc_fixture):\n # see GH#1404\n a = Timestamp("3/12/2012")\n b = Timestamp("3/12/2012", tz=utc_fixture)\n\n msg = "Cannot compare tz-naive and tz-aware timestamps"\n assert not a == b\n assert a != b\n with pytest.raises(TypeError, match=msg):\n a < b\n with pytest.raises(TypeError, match=msg):\n a <= b\n with pytest.raises(TypeError, match=msg):\n a > b\n with pytest.raises(TypeError, match=msg):\n a >= b\n\n assert not b == a\n assert b != a\n with pytest.raises(TypeError, match=msg):\n b < a\n with pytest.raises(TypeError, match=msg):\n b <= a\n with pytest.raises(TypeError, match=msg):\n b > a\n with pytest.raises(TypeError, match=msg):\n b >= a\n\n assert not a == b.to_pydatetime()\n assert not a.to_pydatetime() == b\n\n def test_timestamp_compare_scalars(self):\n # case where ndim == 0\n lhs = np.datetime64(datetime(2013, 12, 6))\n rhs = Timestamp("now")\n nat = Timestamp("nat")\n\n ops = {"gt": "lt", "lt": "gt", "ge": "le", "le": "ge", "eq": "eq", "ne": "ne"}\n\n for left, right in ops.items():\n left_f = getattr(operator, left)\n right_f = getattr(operator, right)\n expected = left_f(lhs, rhs)\n\n result = right_f(rhs, lhs)\n assert result == expected\n\n expected = left_f(rhs, nat)\n result = right_f(nat, rhs)\n assert result == expected\n\n def test_timestamp_compare_with_early_datetime(self):\n # e.g. datetime.min\n stamp = Timestamp("2012-01-01")\n\n assert not stamp == datetime.min\n assert not stamp == datetime(1600, 1, 1)\n assert not stamp == datetime(2700, 1, 1)\n assert stamp != datetime.min\n assert stamp != datetime(1600, 1, 1)\n assert stamp != datetime(2700, 1, 1)\n assert stamp > datetime(1600, 1, 1)\n assert stamp >= datetime(1600, 1, 1)\n assert stamp < datetime(2700, 1, 1)\n assert stamp <= datetime(2700, 1, 1)\n\n other = Timestamp.min.to_pydatetime(warn=False)\n assert other - timedelta(microseconds=1) < Timestamp.min\n\n def test_timestamp_compare_oob_dt64(self):\n us = np.timedelta64(1, "us")\n other = np.datetime64(Timestamp.min).astype("M8[us]")\n\n # This may change if the implementation bound is dropped to match\n # DatetimeArray/DatetimeIndex GH#24124\n assert Timestamp.min > other\n # Note: numpy gets the reversed comparison wrong\n\n other = np.datetime64(Timestamp.max).astype("M8[us]")\n assert Timestamp.max > other # not actually OOB\n assert other < Timestamp.max\n\n assert Timestamp.max < other + us\n # Note: numpy gets the reversed comparison wrong\n\n # GH-42794\n other = datetime(9999, 9, 9)\n assert Timestamp.min < other\n assert other > Timestamp.min\n assert Timestamp.max < other\n assert other > Timestamp.max\n\n other = datetime(1, 1, 1)\n assert Timestamp.max > other\n assert other < Timestamp.max\n assert Timestamp.min > other\n assert other < Timestamp.min\n\n def test_compare_zerodim_array(self, fixed_now_ts):\n # GH#26916\n ts = fixed_now_ts\n dt64 = np.datetime64("2016-01-01", "ns")\n arr = np.array(dt64)\n assert arr.ndim == 0\n\n result = arr < ts\n assert result is np.bool_(True)\n result = arr > ts\n assert result is np.bool_(False)\n\n\ndef test_rich_comparison_with_unsupported_type():\n # Comparisons with unsupported objects should return NotImplemented\n # (it previously raised TypeError, see #24011)\n\n class Inf:\n def __lt__(self, o):\n return False\n\n def __le__(self, o):\n return isinstance(o, Inf)\n\n def __gt__(self, o):\n return not isinstance(o, Inf)\n\n def __ge__(self, o):\n return True\n\n def __eq__(self, other) -> bool:\n return isinstance(other, Inf)\n\n inf = Inf()\n timestamp = Timestamp("2018-11-30")\n\n for left, right in [(inf, timestamp), (timestamp, inf)]:\n assert left > right or left < right\n assert left >= right or left <= right\n assert not left == right # pylint: disable=unneeded-not\n assert left != right\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_comparisons.py
test_comparisons.py
Python
10,059
0.95
0.083067
0.08
react-lib
554
2024-11-18T00:54:02.627807
Apache-2.0
true
cae9ca28eb4ea0b39c34e3422f926c62
import calendar\nfrom datetime import (\n date,\n datetime,\n timedelta,\n timezone,\n)\nimport zoneinfo\n\nimport dateutil.tz\nfrom dateutil.tz import (\n gettz,\n tzoffset,\n tzutc,\n)\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas.compat import PY310\nfrom pandas.errors import OutOfBoundsDatetime\n\nfrom pandas import (\n NA,\n NaT,\n Period,\n Timedelta,\n Timestamp,\n)\n\n\nclass TestTimestampConstructorUnitKeyword:\n @pytest.mark.parametrize("typ", [int, float])\n def test_constructor_int_float_with_YM_unit(self, typ):\n # GH#47266 avoid the conversions in cast_from_unit\n val = typ(150)\n\n ts = Timestamp(val, unit="Y")\n expected = Timestamp("2120-01-01")\n assert ts == expected\n\n ts = Timestamp(val, unit="M")\n expected = Timestamp("1982-07-01")\n assert ts == expected\n\n @pytest.mark.parametrize("typ", [int, float])\n def test_construct_from_int_float_with_unit_out_of_bound_raises(self, typ):\n # GH#50870 make sure we get a OutOfBoundsDatetime instead of OverflowError\n val = typ(150000000000000)\n\n msg = f"cannot convert input {val} with the unit 'D'"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(val, unit="D")\n\n def test_constructor_float_not_round_with_YM_unit_raises(self):\n # GH#47267 avoid the conversions in cast_from-unit\n\n msg = "Conversion of non-round float with unit=[MY] is ambiguous"\n with pytest.raises(ValueError, match=msg):\n Timestamp(150.5, unit="Y")\n\n with pytest.raises(ValueError, match=msg):\n Timestamp(150.5, unit="M")\n\n @pytest.mark.parametrize(\n "value, check_kwargs",\n [\n [946688461000000000, {}],\n [946688461000000000 / 1000, {"unit": "us"}],\n [946688461000000000 / 1_000_000, {"unit": "ms"}],\n [946688461000000000 / 1_000_000_000, {"unit": "s"}],\n [10957, {"unit": "D", "h": 0}],\n [\n (946688461000000000 + 500000) / 1000000000,\n {"unit": "s", "us": 499, "ns": 964},\n ],\n [\n (946688461000000000 + 500000000) / 1000000000,\n {"unit": "s", "us": 500000},\n ],\n [(946688461000000000 + 500000) / 1000000, {"unit": "ms", "us": 500}],\n [(946688461000000000 + 500000) / 1000, {"unit": "us", "us": 500}],\n [(946688461000000000 + 500000000) / 1000000, {"unit": "ms", "us": 500000}],\n [946688461000000000 / 1000.0 + 5, {"unit": "us", "us": 5}],\n [946688461000000000 / 1000.0 + 5000, {"unit": "us", "us": 5000}],\n [946688461000000000 / 1000000.0 + 0.5, {"unit": "ms", "us": 500}],\n [946688461000000000 / 1000000.0 + 0.005, {"unit": "ms", "us": 5, "ns": 5}],\n [946688461000000000 / 1000000000.0 + 0.5, {"unit": "s", "us": 500000}],\n [10957 + 0.5, {"unit": "D", "h": 12}],\n ],\n )\n def test_construct_with_unit(self, value, check_kwargs):\n def check(value, unit=None, h=1, s=1, us=0, ns=0):\n stamp = Timestamp(value, unit=unit)\n assert stamp.year == 2000\n assert stamp.month == 1\n assert stamp.day == 1\n assert stamp.hour == h\n if unit != "D":\n assert stamp.minute == 1\n assert stamp.second == s\n assert stamp.microsecond == us\n else:\n assert stamp.minute == 0\n assert stamp.second == 0\n assert stamp.microsecond == 0\n assert stamp.nanosecond == ns\n\n check(value, **check_kwargs)\n\n\nclass TestTimestampConstructorFoldKeyword:\n def test_timestamp_constructor_invalid_fold_raise(self):\n # Test for GH#25057\n # Valid fold values are only [None, 0, 1]\n msg = "Valid values for the fold argument are None, 0, or 1."\n with pytest.raises(ValueError, match=msg):\n Timestamp(123, fold=2)\n\n def test_timestamp_constructor_pytz_fold_raise(self):\n # Test for GH#25057\n # pytz doesn't support fold. Check that we raise\n # if fold is passed with pytz\n msg = "pytz timezones do not support fold. Please use dateutil timezones."\n tz = pytz.timezone("Europe/London")\n with pytest.raises(ValueError, match=msg):\n Timestamp(datetime(2019, 10, 27, 0, 30, 0, 0), tz=tz, fold=0)\n\n @pytest.mark.parametrize("fold", [0, 1])\n @pytest.mark.parametrize(\n "ts_input",\n [\n 1572136200000000000,\n 1572136200000000000.0,\n np.datetime64(1572136200000000000, "ns"),\n "2019-10-27 01:30:00+01:00",\n datetime(2019, 10, 27, 0, 30, 0, 0, tzinfo=timezone.utc),\n ],\n )\n def test_timestamp_constructor_fold_conflict(self, ts_input, fold):\n # Test for GH#25057\n # Check that we raise on fold conflict\n msg = (\n "Cannot pass fold with possibly unambiguous input: int, float, "\n "numpy.datetime64, str, or timezone-aware datetime-like. "\n "Pass naive datetime-like or build Timestamp from components."\n )\n with pytest.raises(ValueError, match=msg):\n Timestamp(ts_input=ts_input, fold=fold)\n\n @pytest.mark.parametrize("tz", ["dateutil/Europe/London", None])\n @pytest.mark.parametrize("fold", [0, 1])\n def test_timestamp_constructor_retain_fold(self, tz, fold):\n # Test for GH#25057\n # Check that we retain fold\n ts = Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold)\n result = ts.fold\n expected = fold\n assert result == expected\n\n try:\n _tzs = [\n "dateutil/Europe/London",\n zoneinfo.ZoneInfo("Europe/London"),\n ]\n except zoneinfo.ZoneInfoNotFoundError:\n _tzs = ["dateutil/Europe/London"]\n\n @pytest.mark.parametrize("tz", _tzs)\n @pytest.mark.parametrize(\n "ts_input,fold_out",\n [\n (1572136200000000000, 0),\n (1572139800000000000, 1),\n ("2019-10-27 01:30:00+01:00", 0),\n ("2019-10-27 01:30:00+00:00", 1),\n (datetime(2019, 10, 27, 1, 30, 0, 0, fold=0), 0),\n (datetime(2019, 10, 27, 1, 30, 0, 0, fold=1), 1),\n ],\n )\n def test_timestamp_constructor_infer_fold_from_value(self, tz, ts_input, fold_out):\n # Test for GH#25057\n # Check that we infer fold correctly based on timestamps since utc\n # or strings\n ts = Timestamp(ts_input, tz=tz)\n result = ts.fold\n expected = fold_out\n assert result == expected\n\n @pytest.mark.parametrize("tz", ["dateutil/Europe/London"])\n @pytest.mark.parametrize(\n "ts_input,fold,value_out",\n [\n (datetime(2019, 10, 27, 1, 30, 0, 0), 0, 1572136200000000),\n (datetime(2019, 10, 27, 1, 30, 0, 0), 1, 1572139800000000),\n ],\n )\n def test_timestamp_constructor_adjust_value_for_fold(\n self, tz, ts_input, fold, value_out\n ):\n # Test for GH#25057\n # Check that we adjust value for fold correctly\n # based on timestamps since utc\n ts = Timestamp(ts_input, tz=tz, fold=fold)\n result = ts._value\n expected = value_out\n assert result == expected\n\n\nclass TestTimestampConstructorPositionalAndKeywordSupport:\n def test_constructor_positional(self):\n # see GH#10758\n msg = (\n "'NoneType' object cannot be interpreted as an integer"\n if PY310\n else "an integer is required"\n )\n with pytest.raises(TypeError, match=msg):\n Timestamp(2000, 1)\n\n msg = "month must be in 1..12"\n with pytest.raises(ValueError, match=msg):\n Timestamp(2000, 0, 1)\n with pytest.raises(ValueError, match=msg):\n Timestamp(2000, 13, 1)\n\n msg = "day is out of range for month"\n with pytest.raises(ValueError, match=msg):\n Timestamp(2000, 1, 0)\n with pytest.raises(ValueError, match=msg):\n Timestamp(2000, 1, 32)\n\n # see gh-11630\n assert repr(Timestamp(2015, 11, 12)) == repr(Timestamp("20151112"))\n assert repr(Timestamp(2015, 11, 12, 1, 2, 3, 999999)) == repr(\n Timestamp("2015-11-12 01:02:03.999999")\n )\n\n def test_constructor_keyword(self):\n # GH#10758\n msg = "function missing required argument 'day'|Required argument 'day'"\n with pytest.raises(TypeError, match=msg):\n Timestamp(year=2000, month=1)\n\n msg = "month must be in 1..12"\n with pytest.raises(ValueError, match=msg):\n Timestamp(year=2000, month=0, day=1)\n with pytest.raises(ValueError, match=msg):\n Timestamp(year=2000, month=13, day=1)\n\n msg = "day is out of range for month"\n with pytest.raises(ValueError, match=msg):\n Timestamp(year=2000, month=1, day=0)\n with pytest.raises(ValueError, match=msg):\n Timestamp(year=2000, month=1, day=32)\n\n assert repr(Timestamp(year=2015, month=11, day=12)) == repr(\n Timestamp("20151112")\n )\n\n assert repr(\n Timestamp(\n year=2015,\n month=11,\n day=12,\n hour=1,\n minute=2,\n second=3,\n microsecond=999999,\n )\n ) == repr(Timestamp("2015-11-12 01:02:03.999999"))\n\n @pytest.mark.parametrize(\n "arg",\n [\n "year",\n "month",\n "day",\n "hour",\n "minute",\n "second",\n "microsecond",\n "nanosecond",\n ],\n )\n def test_invalid_date_kwarg_with_string_input(self, arg):\n kwarg = {arg: 1}\n msg = "Cannot pass a date attribute keyword argument"\n with pytest.raises(ValueError, match=msg):\n Timestamp("2010-10-10 12:59:59.999999999", **kwarg)\n\n @pytest.mark.parametrize("kwargs", [{}, {"year": 2020}, {"year": 2020, "month": 1}])\n def test_constructor_missing_keyword(self, kwargs):\n # GH#31200\n\n # The exact error message of datetime() depends on its version\n msg1 = r"function missing required argument '(year|month|day)' \(pos [123]\)"\n msg2 = r"Required argument '(year|month|day)' \(pos [123]\) not found"\n msg = "|".join([msg1, msg2])\n\n with pytest.raises(TypeError, match=msg):\n Timestamp(**kwargs)\n\n def test_constructor_positional_with_tzinfo(self):\n # GH#31929\n ts = Timestamp(2020, 12, 31, tzinfo=timezone.utc)\n expected = Timestamp("2020-12-31", tzinfo=timezone.utc)\n assert ts == expected\n\n @pytest.mark.parametrize("kwd", ["nanosecond", "microsecond", "second", "minute"])\n def test_constructor_positional_keyword_mixed_with_tzinfo(self, kwd, request):\n # TODO: if we passed microsecond with a keyword we would mess up\n # xref GH#45307\n if kwd != "nanosecond":\n # nanosecond is keyword-only as of 2.0, others are not\n mark = pytest.mark.xfail(reason="GH#45307")\n request.applymarker(mark)\n\n kwargs = {kwd: 4}\n ts = Timestamp(2020, 12, 31, tzinfo=timezone.utc, **kwargs)\n\n td_kwargs = {kwd + "s": 4}\n td = Timedelta(**td_kwargs)\n expected = Timestamp("2020-12-31", tz=timezone.utc) + td\n assert ts == expected\n\n\nclass TestTimestampClassMethodConstructors:\n # Timestamp constructors other than __new__\n\n def test_constructor_strptime(self):\n # GH#25016\n # Test support for Timestamp.strptime\n fmt = "%Y%m%d-%H%M%S-%f%z"\n ts = "20190129-235348-000001+0000"\n msg = r"Timestamp.strptime\(\) is not implemented"\n with pytest.raises(NotImplementedError, match=msg):\n Timestamp.strptime(ts, fmt)\n\n def test_constructor_fromisocalendar(self):\n # GH#30395\n expected_timestamp = Timestamp("2000-01-03 00:00:00")\n expected_stdlib = datetime.fromisocalendar(2000, 1, 1)\n result = Timestamp.fromisocalendar(2000, 1, 1)\n assert result == expected_timestamp\n assert result == expected_stdlib\n assert isinstance(result, Timestamp)\n\n def test_constructor_fromordinal(self):\n base = datetime(2000, 1, 1)\n\n ts = Timestamp.fromordinal(base.toordinal())\n assert base == ts\n assert base.toordinal() == ts.toordinal()\n\n ts = Timestamp.fromordinal(base.toordinal(), tz="US/Eastern")\n assert Timestamp("2000-01-01", tz="US/Eastern") == ts\n assert base.toordinal() == ts.toordinal()\n\n # GH#3042\n dt = datetime(2011, 4, 16, 0, 0)\n ts = Timestamp.fromordinal(dt.toordinal())\n assert ts.to_pydatetime() == dt\n\n # with a tzinfo\n stamp = Timestamp("2011-4-16", tz="US/Eastern")\n dt_tz = stamp.to_pydatetime()\n ts = Timestamp.fromordinal(dt_tz.toordinal(), tz="US/Eastern")\n assert ts.to_pydatetime() == dt_tz\n\n def test_now(self):\n # GH#9000\n ts_from_string = Timestamp("now")\n ts_from_method = Timestamp.now()\n ts_datetime = datetime.now()\n\n ts_from_string_tz = Timestamp("now", tz="US/Eastern")\n ts_from_method_tz = Timestamp.now(tz="US/Eastern")\n\n # Check that the delta between the times is less than 1s (arbitrarily\n # small)\n delta = Timedelta(seconds=1)\n assert abs(ts_from_method - ts_from_string) < delta\n assert abs(ts_datetime - ts_from_method) < delta\n assert abs(ts_from_method_tz - ts_from_string_tz) < delta\n assert (\n abs(\n ts_from_string_tz.tz_localize(None)\n - ts_from_method_tz.tz_localize(None)\n )\n < delta\n )\n\n def test_today(self):\n ts_from_string = Timestamp("today")\n ts_from_method = Timestamp.today()\n ts_datetime = datetime.today()\n\n ts_from_string_tz = Timestamp("today", tz="US/Eastern")\n ts_from_method_tz = Timestamp.today(tz="US/Eastern")\n\n # Check that the delta between the times is less than 1s (arbitrarily\n # small)\n delta = Timedelta(seconds=1)\n assert abs(ts_from_method - ts_from_string) < delta\n assert abs(ts_datetime - ts_from_method) < delta\n assert abs(ts_from_method_tz - ts_from_string_tz) < delta\n assert (\n abs(\n ts_from_string_tz.tz_localize(None)\n - ts_from_method_tz.tz_localize(None)\n )\n < delta\n )\n\n\nclass TestTimestampResolutionInference:\n def test_construct_from_time_unit(self):\n # GH#54097 only passing a time component, no date\n ts = Timestamp("01:01:01.111")\n assert ts.unit == "ms"\n\n def test_constructor_str_infer_reso(self):\n # non-iso8601 path\n\n # _parse_delimited_date path\n ts = Timestamp("01/30/2023")\n assert ts.unit == "s"\n\n # _parse_dateabbr_string path\n ts = Timestamp("2015Q1")\n assert ts.unit == "s"\n\n # dateutil_parse path\n ts = Timestamp("2016-01-01 1:30:01 PM")\n assert ts.unit == "s"\n\n ts = Timestamp("2016 June 3 15:25:01.345")\n assert ts.unit == "ms"\n\n ts = Timestamp("300-01-01")\n assert ts.unit == "s"\n\n ts = Timestamp("300 June 1:30:01.300")\n assert ts.unit == "ms"\n\n # dateutil path -> don't drop trailing zeros\n ts = Timestamp("01-01-2013T00:00:00.000000000+0000")\n assert ts.unit == "ns"\n\n ts = Timestamp("2016/01/02 03:04:05.001000 UTC")\n assert ts.unit == "us"\n\n # higher-than-nanosecond -> we drop the trailing bits\n ts = Timestamp("01-01-2013T00:00:00.000000002100+0000")\n assert ts == Timestamp("01-01-2013T00:00:00.000000002+0000")\n assert ts.unit == "ns"\n\n # GH#56208 minute reso through the ISO8601 path with tz offset\n ts = Timestamp("2020-01-01 00:00+00:00")\n assert ts.unit == "s"\n\n ts = Timestamp("2020-01-01 00+00:00")\n assert ts.unit == "s"\n\n @pytest.mark.parametrize("method", ["now", "today"])\n def test_now_today_unit(self, method):\n # GH#55879\n ts_from_method = getattr(Timestamp, method)()\n ts_from_string = Timestamp(method)\n assert ts_from_method.unit == ts_from_string.unit == "us"\n\n\nclass TestTimestampConstructors:\n def test_weekday_but_no_day_raises(self):\n # GH#52659\n msg = "Parsing datetimes with weekday but no day information is not supported"\n with pytest.raises(ValueError, match=msg):\n Timestamp("2023 Sept Thu")\n\n def test_construct_from_string_invalid_raises(self):\n # dateutil (weirdly) parses "200622-12-31" as\n # datetime(2022, 6, 20, 12, 0, tzinfo=tzoffset(None, -111600)\n # which besides being mis-parsed, is a tzoffset that will cause\n # str(ts) to raise ValueError. Ensure we raise in the constructor\n # instead.\n # see test_to_datetime_malformed_raise for analogous to_datetime test\n with pytest.raises(ValueError, match="gives an invalid tzoffset"):\n Timestamp("200622-12-31")\n\n def test_constructor_from_iso8601_str_with_offset_reso(self):\n # GH#49737\n ts = Timestamp("2016-01-01 04:05:06-01:00")\n assert ts.unit == "s"\n\n ts = Timestamp("2016-01-01 04:05:06.000-01:00")\n assert ts.unit == "ms"\n\n ts = Timestamp("2016-01-01 04:05:06.000000-01:00")\n assert ts.unit == "us"\n\n ts = Timestamp("2016-01-01 04:05:06.000000001-01:00")\n assert ts.unit == "ns"\n\n def test_constructor_from_date_second_reso(self):\n # GH#49034 constructing from a pydate object gets lowest supported\n # reso, i.e. seconds\n obj = date(2012, 9, 1)\n ts = Timestamp(obj)\n assert ts.unit == "s"\n\n def test_constructor_datetime64_with_tz(self):\n # GH#42288, GH#24559\n dt = np.datetime64("1970-01-01 05:00:00")\n tzstr = "UTC+05:00"\n\n # pre-2.0 this interpreted dt as a UTC time. in 2.0 this is treated\n # as a wall-time, consistent with DatetimeIndex behavior\n ts = Timestamp(dt, tz=tzstr)\n\n alt = Timestamp(dt).tz_localize(tzstr)\n assert ts == alt\n assert ts.hour == 5\n\n def test_constructor(self):\n base_str = "2014-07-01 09:00"\n base_dt = datetime(2014, 7, 1, 9)\n base_expected = 1_404_205_200_000_000_000\n\n # confirm base representation is correct\n assert calendar.timegm(base_dt.timetuple()) * 1_000_000_000 == base_expected\n\n tests = [\n (base_str, base_dt, base_expected),\n (\n "2014-07-01 10:00",\n datetime(2014, 7, 1, 10),\n base_expected + 3600 * 1_000_000_000,\n ),\n (\n "2014-07-01 09:00:00.000008000",\n datetime(2014, 7, 1, 9, 0, 0, 8),\n base_expected + 8000,\n ),\n (\n "2014-07-01 09:00:00.000000005",\n Timestamp("2014-07-01 09:00:00.000000005"),\n base_expected + 5,\n ),\n ]\n\n timezones = [\n (None, 0),\n ("UTC", 0),\n (pytz.utc, 0),\n ("Asia/Tokyo", 9),\n ("US/Eastern", -4),\n ("dateutil/US/Pacific", -7),\n (pytz.FixedOffset(-180), -3),\n (dateutil.tz.tzoffset(None, 18000), 5),\n ]\n\n for date_str, date_obj, expected in tests:\n for result in [Timestamp(date_str), Timestamp(date_obj)]:\n result = result.as_unit("ns") # test originally written before non-nano\n # only with timestring\n assert result.as_unit("ns")._value == expected\n\n # re-creation shouldn't affect to internal value\n result = Timestamp(result)\n assert result.as_unit("ns")._value == expected\n\n # with timezone\n for tz, offset in timezones:\n for result in [Timestamp(date_str, tz=tz), Timestamp(date_obj, tz=tz)]:\n result = result.as_unit(\n "ns"\n ) # test originally written before non-nano\n expected_tz = expected - offset * 3600 * 1_000_000_000\n assert result.as_unit("ns")._value == expected_tz\n\n # should preserve tz\n result = Timestamp(result)\n assert result.as_unit("ns")._value == expected_tz\n\n # should convert to UTC\n if tz is not None:\n result = Timestamp(result).tz_convert("UTC")\n else:\n result = Timestamp(result, tz="UTC")\n expected_utc = expected - offset * 3600 * 1_000_000_000\n assert result.as_unit("ns")._value == expected_utc\n\n def test_constructor_with_stringoffset(self):\n # GH 7833\n base_str = "2014-07-01 11:00:00+02:00"\n base_dt = datetime(2014, 7, 1, 9)\n base_expected = 1_404_205_200_000_000_000\n\n # confirm base representation is correct\n assert calendar.timegm(base_dt.timetuple()) * 1_000_000_000 == base_expected\n\n tests = [\n (base_str, base_expected),\n ("2014-07-01 12:00:00+02:00", base_expected + 3600 * 1_000_000_000),\n ("2014-07-01 11:00:00.000008000+02:00", base_expected + 8000),\n ("2014-07-01 11:00:00.000000005+02:00", base_expected + 5),\n ]\n\n timezones = [\n (None, 0),\n ("UTC", 0),\n (pytz.utc, 0),\n ("Asia/Tokyo", 9),\n ("US/Eastern", -4),\n ("dateutil/US/Pacific", -7),\n (pytz.FixedOffset(-180), -3),\n (dateutil.tz.tzoffset(None, 18000), 5),\n ]\n\n for date_str, expected in tests:\n for result in [Timestamp(date_str)]:\n # only with timestring\n assert result.as_unit("ns")._value == expected\n\n # re-creation shouldn't affect to internal value\n result = Timestamp(result)\n assert result.as_unit("ns")._value == expected\n\n # with timezone\n for tz, offset in timezones:\n result = Timestamp(date_str, tz=tz)\n expected_tz = expected\n assert result.as_unit("ns")._value == expected_tz\n\n # should preserve tz\n result = Timestamp(result)\n assert result.as_unit("ns")._value == expected_tz\n\n # should convert to UTC\n result = Timestamp(result).tz_convert("UTC")\n expected_utc = expected\n assert result.as_unit("ns")._value == expected_utc\n\n # This should be 2013-11-01 05:00 in UTC\n # converted to Chicago tz\n result = Timestamp("2013-11-01 00:00:00-0500", tz="America/Chicago")\n assert result._value == Timestamp("2013-11-01 05:00")._value\n expected = "Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')"\n assert repr(result) == expected\n assert result == eval(repr(result))\n\n # This should be 2013-11-01 05:00 in UTC\n # converted to Tokyo tz (+09:00)\n result = Timestamp("2013-11-01 00:00:00-0500", tz="Asia/Tokyo")\n assert result._value == Timestamp("2013-11-01 05:00")._value\n expected = "Timestamp('2013-11-01 14:00:00+0900', tz='Asia/Tokyo')"\n assert repr(result) == expected\n assert result == eval(repr(result))\n\n # GH11708\n # This should be 2015-11-18 10:00 in UTC\n # converted to Asia/Katmandu\n result = Timestamp("2015-11-18 15:45:00+05:45", tz="Asia/Katmandu")\n assert result._value == Timestamp("2015-11-18 10:00")._value\n expected = "Timestamp('2015-11-18 15:45:00+0545', tz='Asia/Katmandu')"\n assert repr(result) == expected\n assert result == eval(repr(result))\n\n # This should be 2015-11-18 10:00 in UTC\n # converted to Asia/Kolkata\n result = Timestamp("2015-11-18 15:30:00+05:30", tz="Asia/Kolkata")\n assert result._value == Timestamp("2015-11-18 10:00")._value\n expected = "Timestamp('2015-11-18 15:30:00+0530', tz='Asia/Kolkata')"\n assert repr(result) == expected\n assert result == eval(repr(result))\n\n def test_constructor_invalid(self):\n msg = "Cannot convert input"\n with pytest.raises(TypeError, match=msg):\n Timestamp(slice(2))\n msg = "Cannot convert Period"\n with pytest.raises(ValueError, match=msg):\n Timestamp(Period("1000-01-01"))\n\n def test_constructor_invalid_tz(self):\n # GH#17690\n msg = (\n "Argument 'tzinfo' has incorrect type "\n r"\(expected datetime.tzinfo, got str\)"\n )\n with pytest.raises(TypeError, match=msg):\n Timestamp("2017-10-22", tzinfo="US/Eastern")\n\n msg = "at most one of"\n with pytest.raises(ValueError, match=msg):\n Timestamp("2017-10-22", tzinfo=pytz.utc, tz="UTC")\n\n msg = "Cannot pass a date attribute keyword argument when passing a date string"\n with pytest.raises(ValueError, match=msg):\n # GH#5168\n # case where user tries to pass tz as an arg, not kwarg, gets\n # interpreted as `year`\n Timestamp("2012-01-01", "US/Pacific")\n\n def test_constructor_tz_or_tzinfo(self):\n # GH#17943, GH#17690, GH#5168\n stamps = [\n Timestamp(year=2017, month=10, day=22, tz="UTC"),\n Timestamp(year=2017, month=10, day=22, tzinfo=pytz.utc),\n Timestamp(year=2017, month=10, day=22, tz=pytz.utc),\n Timestamp(datetime(2017, 10, 22), tzinfo=pytz.utc),\n Timestamp(datetime(2017, 10, 22), tz="UTC"),\n Timestamp(datetime(2017, 10, 22), tz=pytz.utc),\n ]\n assert all(ts == stamps[0] for ts in stamps)\n\n @pytest.mark.parametrize(\n "result",\n [\n Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), nanosecond=1),\n Timestamp(\n year=2000,\n month=1,\n day=2,\n hour=3,\n minute=4,\n second=5,\n microsecond=6,\n nanosecond=1,\n ),\n Timestamp(\n year=2000,\n month=1,\n day=2,\n hour=3,\n minute=4,\n second=5,\n microsecond=6,\n nanosecond=1,\n tz="UTC",\n ),\n Timestamp(2000, 1, 2, 3, 4, 5, 6, None, nanosecond=1),\n Timestamp(2000, 1, 2, 3, 4, 5, 6, tz=pytz.UTC, nanosecond=1),\n ],\n )\n def test_constructor_nanosecond(self, result):\n # GH 18898\n # As of 2.0 (GH 49416), nanosecond should not be accepted positionally\n expected = Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), tz=result.tz)\n expected = expected + Timedelta(nanoseconds=1)\n assert result == expected\n\n @pytest.mark.parametrize("z", ["Z0", "Z00"])\n def test_constructor_invalid_Z0_isostring(self, z):\n # GH 8910\n msg = f"Unknown datetime string format, unable to parse: 2014-11-02 01:00{z}"\n with pytest.raises(ValueError, match=msg):\n Timestamp(f"2014-11-02 01:00{z}")\n\n def test_out_of_bounds_integer_value(self):\n # GH#26651 check that we raise OutOfBoundsDatetime, not OverflowError\n msg = str(Timestamp.max._value * 2)\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(Timestamp.max._value * 2)\n msg = str(Timestamp.min._value * 2)\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(Timestamp.min._value * 2)\n\n def test_out_of_bounds_value(self):\n one_us = np.timedelta64(1).astype("timedelta64[us]")\n\n # By definition we can't go out of bounds in [ns], so we\n # convert the datetime64s to [us] so we can go out of bounds\n min_ts_us = np.datetime64(Timestamp.min).astype("M8[us]") + one_us\n max_ts_us = np.datetime64(Timestamp.max).astype("M8[us]")\n\n # No error for the min/max datetimes\n Timestamp(min_ts_us)\n Timestamp(max_ts_us)\n\n # We used to raise on these before supporting non-nano\n us_val = NpyDatetimeUnit.NPY_FR_us.value\n assert Timestamp(min_ts_us - one_us)._creso == us_val\n assert Timestamp(max_ts_us + one_us)._creso == us_val\n\n # https://github.com/numpy/numpy/issues/22346 for why\n # we can't use the same construction as above with minute resolution\n\n # too_low, too_high are the _just_ outside the range of M8[s]\n too_low = np.datetime64("-292277022657-01-27T08:29", "m")\n too_high = np.datetime64("292277026596-12-04T15:31", "m")\n\n msg = "Out of bounds"\n # One us less than the minimum is an error\n with pytest.raises(ValueError, match=msg):\n Timestamp(too_low)\n\n # One us more than the maximum is an error\n with pytest.raises(ValueError, match=msg):\n Timestamp(too_high)\n\n def test_out_of_bounds_string(self):\n msg = "Cannot cast .* to unit='ns' without overflow"\n with pytest.raises(ValueError, match=msg):\n Timestamp("1676-01-01").as_unit("ns")\n with pytest.raises(ValueError, match=msg):\n Timestamp("2263-01-01").as_unit("ns")\n\n ts = Timestamp("2263-01-01")\n assert ts.unit == "s"\n\n ts = Timestamp("1676-01-01")\n assert ts.unit == "s"\n\n def test_barely_out_of_bounds(self):\n # GH#19529\n # GH#19382 close enough to bounds that dropping nanos would result\n # in an in-bounds datetime\n msg = "Out of bounds nanosecond timestamp: 2262-04-11 23:47:16"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp("2262-04-11 23:47:16.854775808")\n\n @pytest.mark.skip_ubsan\n def test_bounds_with_different_units(self):\n out_of_bounds_dates = ("1677-09-21", "2262-04-12")\n\n time_units = ("D", "h", "m", "s", "ms", "us")\n\n for date_string in out_of_bounds_dates:\n for unit in time_units:\n dt64 = np.datetime64(date_string, unit)\n ts = Timestamp(dt64)\n if unit in ["s", "ms", "us"]:\n # We can preserve the input unit\n assert ts._value == dt64.view("i8")\n else:\n # we chose the closest unit that we _do_ support\n assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n # With more extreme cases, we can't even fit inside second resolution\n info = np.iinfo(np.int64)\n msg = "Out of bounds second timestamp:"\n for value in [info.min + 1, info.max]:\n for unit in ["D", "h", "m"]:\n dt64 = np.datetime64(value, unit)\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(dt64)\n\n in_bounds_dates = ("1677-09-23", "2262-04-11")\n\n for date_string in in_bounds_dates:\n for unit in time_units:\n dt64 = np.datetime64(date_string, unit)\n Timestamp(dt64)\n\n @pytest.mark.parametrize("arg", ["001-01-01", "0001-01-01"])\n def test_out_of_bounds_string_consistency(self, arg):\n # GH 15829\n msg = "Cannot cast 0001-01-01 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(arg).as_unit("ns")\n\n ts = Timestamp(arg)\n assert ts.unit == "s"\n assert ts.year == ts.month == ts.day == 1\n\n def test_min_valid(self):\n # Ensure that Timestamp.min is a valid Timestamp\n Timestamp(Timestamp.min)\n\n def test_max_valid(self):\n # Ensure that Timestamp.max is a valid Timestamp\n Timestamp(Timestamp.max)\n\n @pytest.mark.parametrize("offset", ["+0300", "+0200"])\n def test_construct_timestamp_near_dst(self, offset):\n # GH 20854\n expected = Timestamp(f"2016-10-30 03:00:00{offset}", tz="Europe/Helsinki")\n result = Timestamp(expected).tz_convert("Europe/Helsinki")\n assert result == expected\n\n @pytest.mark.parametrize(\n "arg", ["2013/01/01 00:00:00+09:00", "2013-01-01 00:00:00+09:00"]\n )\n def test_construct_with_different_string_format(self, arg):\n # GH 12064\n result = Timestamp(arg)\n expected = Timestamp(datetime(2013, 1, 1), tz=pytz.FixedOffset(540))\n assert result == expected\n\n @pytest.mark.parametrize("box", [datetime, Timestamp])\n def test_raise_tz_and_tzinfo_in_datetime_input(self, box):\n # GH 23579\n kwargs = {"year": 2018, "month": 1, "day": 1, "tzinfo": pytz.utc}\n msg = "Cannot pass a datetime or Timestamp"\n with pytest.raises(ValueError, match=msg):\n Timestamp(box(**kwargs), tz="US/Pacific")\n msg = "Cannot pass a datetime or Timestamp"\n with pytest.raises(ValueError, match=msg):\n Timestamp(box(**kwargs), tzinfo=pytz.timezone("US/Pacific"))\n\n def test_dont_convert_dateutil_utc_to_pytz_utc(self):\n result = Timestamp(datetime(2018, 1, 1), tz=tzutc())\n expected = Timestamp(datetime(2018, 1, 1)).tz_localize(tzutc())\n assert result == expected\n\n def test_constructor_subclassed_datetime(self):\n # GH 25851\n # ensure that subclassed datetime works for\n # Timestamp creation\n class SubDatetime(datetime):\n pass\n\n data = SubDatetime(2000, 1, 1)\n result = Timestamp(data)\n expected = Timestamp(2000, 1, 1)\n assert result == expected\n\n def test_timestamp_constructor_tz_utc(self):\n utc_stamp = Timestamp("3/11/2012 05:00", tz="utc")\n assert utc_stamp.tzinfo is timezone.utc\n assert utc_stamp.hour == 5\n\n utc_stamp = Timestamp("3/11/2012 05:00").tz_localize("utc")\n assert utc_stamp.hour == 5\n\n def test_timestamp_to_datetime_tzoffset(self):\n tzinfo = tzoffset(None, 7200)\n expected = Timestamp("3/11/2012 04:00", tz=tzinfo)\n result = Timestamp(expected.to_pydatetime())\n assert expected == result\n\n def test_timestamp_constructor_near_dst_boundary(self):\n # GH#11481 & GH#15777\n # Naive string timestamps were being localized incorrectly\n # with tz_convert_from_utc_single instead of tz_localize_to_utc\n\n for tz in ["Europe/Brussels", "Europe/Prague"]:\n result = Timestamp("2015-10-25 01:00", tz=tz)\n expected = Timestamp("2015-10-25 01:00").tz_localize(tz)\n assert result == expected\n\n msg = "Cannot infer dst time from 2015-10-25 02:00:00"\n with pytest.raises(pytz.AmbiguousTimeError, match=msg):\n Timestamp("2015-10-25 02:00", tz=tz)\n\n result = Timestamp("2017-03-26 01:00", tz="Europe/Paris")\n expected = Timestamp("2017-03-26 01:00").tz_localize("Europe/Paris")\n assert result == expected\n\n msg = "2017-03-26 02:00"\n with pytest.raises(pytz.NonExistentTimeError, match=msg):\n Timestamp("2017-03-26 02:00", tz="Europe/Paris")\n\n # GH#11708\n naive = Timestamp("2015-11-18 10:00:00")\n result = naive.tz_localize("UTC").tz_convert("Asia/Kolkata")\n expected = Timestamp("2015-11-18 15:30:00+0530", tz="Asia/Kolkata")\n assert result == expected\n\n # GH#15823\n result = Timestamp("2017-03-26 00:00", tz="Europe/Paris")\n expected = Timestamp("2017-03-26 00:00:00+0100", tz="Europe/Paris")\n assert result == expected\n\n result = Timestamp("2017-03-26 01:00", tz="Europe/Paris")\n expected = Timestamp("2017-03-26 01:00:00+0100", tz="Europe/Paris")\n assert result == expected\n\n msg = "2017-03-26 02:00"\n with pytest.raises(pytz.NonExistentTimeError, match=msg):\n Timestamp("2017-03-26 02:00", tz="Europe/Paris")\n\n result = Timestamp("2017-03-26 02:00:00+0100", tz="Europe/Paris")\n naive = Timestamp(result.as_unit("ns")._value)\n expected = naive.tz_localize("UTC").tz_convert("Europe/Paris")\n assert result == expected\n\n result = Timestamp("2017-03-26 03:00", tz="Europe/Paris")\n expected = Timestamp("2017-03-26 03:00:00+0200", tz="Europe/Paris")\n assert result == expected\n\n @pytest.mark.parametrize(\n "tz",\n [\n pytz.timezone("US/Eastern"),\n gettz("US/Eastern"),\n "US/Eastern",\n "dateutil/US/Eastern",\n ],\n )\n def test_timestamp_constructed_by_date_and_tz(self, tz):\n # GH#2993, Timestamp cannot be constructed by datetime.date\n # and tz correctly\n\n result = Timestamp(date(2012, 3, 11), tz=tz)\n\n expected = Timestamp("3/11/2012", tz=tz)\n assert result.hour == expected.hour\n assert result == expected\n\n\ndef test_constructor_ambiguous_dst():\n # GH 24329\n # Make sure that calling Timestamp constructor\n # on Timestamp created from ambiguous time\n # doesn't change Timestamp.value\n ts = Timestamp(1382835600000000000, tz="dateutil/Europe/London")\n expected = ts._value\n result = Timestamp(ts)._value\n assert result == expected\n\n\n@pytest.mark.parametrize("epoch", [1552211999999999872, 1552211999999999999])\ndef test_constructor_before_dst_switch(epoch):\n # GH 31043\n # Make sure that calling Timestamp constructor\n # on time just before DST switch doesn't lead to\n # nonexistent time or value change\n ts = Timestamp(epoch, tz="dateutil/America/Los_Angeles")\n result = ts.tz.dst(ts)\n expected = timedelta(seconds=0)\n assert Timestamp(ts)._value == epoch\n assert result == expected\n\n\ndef test_timestamp_constructor_identity():\n # Test for #30543\n expected = Timestamp("2017-01-01T12")\n result = Timestamp(expected)\n assert result is expected\n\n\n@pytest.mark.parametrize("nano", [-1, 1000])\ndef test_timestamp_nano_range(nano):\n # GH 48255\n with pytest.raises(ValueError, match="nanosecond must be in 0..999"):\n Timestamp(year=2022, month=1, day=1, nanosecond=nano)\n\n\ndef test_non_nano_value():\n # https://github.com/pandas-dev/pandas/issues/49076\n result = Timestamp("1800-01-01", unit="s").value\n # `.value` shows nanoseconds, even though unit is 's'\n assert result == -5364662400000000000\n\n # out-of-nanoseconds-bounds `.value` raises informative message\n msg = (\n r"Cannot convert Timestamp to nanoseconds without overflow. "\n r"Use `.asm8.view\('i8'\)` to cast represent Timestamp in its "\n r"own unit \(here, s\).$"\n )\n ts = Timestamp("0300-01-01")\n with pytest.raises(OverflowError, match=msg):\n ts.value\n # check that the suggested workaround actually works\n result = ts.asm8.view("i8")\n assert result == -52700112000\n\n\n@pytest.mark.parametrize("na_value", [None, np.nan, np.datetime64("NaT"), NaT, NA])\ndef test_timestamp_constructor_na_value(na_value):\n # GH45481\n result = Timestamp(na_value)\n expected = NaT\n assert result is expected\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_constructors.py
test_constructors.py
Python
39,486
0.95
0.10206
0.152392
node-utils
568
2025-03-10T19:10:35.086126
MIT
true
9440ab1c9c79a51d51798f894343f2d0
from datetime import datetime\nimport pprint\n\nimport dateutil.tz\nimport pytest\nimport pytz # a test below uses pytz but only inside a `eval` call\n\nfrom pandas import Timestamp\n\nts_no_ns = Timestamp(\n year=2019,\n month=5,\n day=18,\n hour=15,\n minute=17,\n second=8,\n microsecond=132263,\n)\nts_no_ns_year1 = Timestamp(\n year=1,\n month=5,\n day=18,\n hour=15,\n minute=17,\n second=8,\n microsecond=132263,\n)\nts_ns = Timestamp(\n year=2019,\n month=5,\n day=18,\n hour=15,\n minute=17,\n second=8,\n microsecond=132263,\n nanosecond=123,\n)\nts_ns_tz = Timestamp(\n year=2019,\n month=5,\n day=18,\n hour=15,\n minute=17,\n second=8,\n microsecond=132263,\n nanosecond=123,\n tz="UTC",\n)\nts_no_us = Timestamp(\n year=2019,\n month=5,\n day=18,\n hour=15,\n minute=17,\n second=8,\n microsecond=0,\n nanosecond=123,\n)\n\n\n@pytest.mark.parametrize(\n "ts, timespec, expected_iso",\n [\n (ts_no_ns, "auto", "2019-05-18T15:17:08.132263"),\n (ts_no_ns, "seconds", "2019-05-18T15:17:08"),\n (ts_no_ns, "nanoseconds", "2019-05-18T15:17:08.132263000"),\n (ts_no_ns_year1, "seconds", "0001-05-18T15:17:08"),\n (ts_no_ns_year1, "nanoseconds", "0001-05-18T15:17:08.132263000"),\n (ts_ns, "auto", "2019-05-18T15:17:08.132263123"),\n (ts_ns, "hours", "2019-05-18T15"),\n (ts_ns, "minutes", "2019-05-18T15:17"),\n (ts_ns, "seconds", "2019-05-18T15:17:08"),\n (ts_ns, "milliseconds", "2019-05-18T15:17:08.132"),\n (ts_ns, "microseconds", "2019-05-18T15:17:08.132263"),\n (ts_ns, "nanoseconds", "2019-05-18T15:17:08.132263123"),\n (ts_ns_tz, "auto", "2019-05-18T15:17:08.132263123+00:00"),\n (ts_ns_tz, "hours", "2019-05-18T15+00:00"),\n (ts_ns_tz, "minutes", "2019-05-18T15:17+00:00"),\n (ts_ns_tz, "seconds", "2019-05-18T15:17:08+00:00"),\n (ts_ns_tz, "milliseconds", "2019-05-18T15:17:08.132+00:00"),\n (ts_ns_tz, "microseconds", "2019-05-18T15:17:08.132263+00:00"),\n (ts_ns_tz, "nanoseconds", "2019-05-18T15:17:08.132263123+00:00"),\n (ts_no_us, "auto", "2019-05-18T15:17:08.000000123"),\n ],\n)\ndef test_isoformat(ts, timespec, expected_iso):\n assert ts.isoformat(timespec=timespec) == expected_iso\n\n\nclass TestTimestampRendering:\n timezones = ["UTC", "Asia/Tokyo", "US/Eastern", "dateutil/America/Los_Angeles"]\n\n @pytest.mark.parametrize("tz", timezones)\n @pytest.mark.parametrize("freq", ["D", "M", "S", "N"])\n @pytest.mark.parametrize(\n "date", ["2014-03-07", "2014-01-01 09:00", "2014-01-01 00:00:00.000000001"]\n )\n def test_repr(self, date, freq, tz):\n # avoid to match with timezone name\n freq_repr = f"'{freq}'"\n if tz.startswith("dateutil"):\n tz_repr = tz.replace("dateutil", "")\n else:\n tz_repr = tz\n\n date_only = Timestamp(date)\n assert date in repr(date_only)\n assert tz_repr not in repr(date_only)\n assert freq_repr not in repr(date_only)\n assert date_only == eval(repr(date_only))\n\n date_tz = Timestamp(date, tz=tz)\n assert date in repr(date_tz)\n assert tz_repr in repr(date_tz)\n assert freq_repr not in repr(date_tz)\n assert date_tz == eval(repr(date_tz))\n\n def test_repr_utcoffset(self):\n # This can cause the tz field to be populated, but it's redundant to\n # include this information in the date-string.\n date_with_utc_offset = Timestamp("2014-03-13 00:00:00-0400", tz=None)\n assert "2014-03-13 00:00:00-0400" in repr(date_with_utc_offset)\n assert "tzoffset" not in repr(date_with_utc_offset)\n assert "UTC-04:00" in repr(date_with_utc_offset)\n expr = repr(date_with_utc_offset)\n assert date_with_utc_offset == eval(expr)\n\n def test_timestamp_repr_pre1900(self):\n # pre-1900\n stamp = Timestamp("1850-01-01", tz="US/Eastern")\n repr(stamp)\n\n iso8601 = "1850-01-01 01:23:45.012345"\n stamp = Timestamp(iso8601, tz="US/Eastern")\n result = repr(stamp)\n assert iso8601 in result\n\n def test_pprint(self):\n # GH#12622\n nested_obj = {"foo": 1, "bar": [{"w": {"a": Timestamp("2011-01-01")}}] * 10}\n result = pprint.pformat(nested_obj, width=50)\n expected = r"""{'bar': [{'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}},\n {'w': {'a': Timestamp('2011-01-01 00:00:00')}}],\n 'foo': 1}"""\n assert result == expected\n\n def test_to_timestamp_repr_is_code(self):\n zs = [\n Timestamp("99-04-17 00:00:00", tz="UTC"),\n Timestamp("2001-04-17 00:00:00", tz="UTC"),\n Timestamp("2001-04-17 00:00:00", tz="America/Los_Angeles"),\n Timestamp("2001-04-17 00:00:00", tz=None),\n ]\n for z in zs:\n assert eval(repr(z)) == z\n\n def test_repr_matches_pydatetime_no_tz(self):\n dt_date = datetime(2013, 1, 2)\n assert str(dt_date) == str(Timestamp(dt_date))\n\n dt_datetime = datetime(2013, 1, 2, 12, 1, 3)\n assert str(dt_datetime) == str(Timestamp(dt_datetime))\n\n dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45)\n assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))\n\n ts_nanos_only = Timestamp(200)\n assert str(ts_nanos_only) == "1970-01-01 00:00:00.000000200"\n\n ts_nanos_micros = Timestamp(1200)\n assert str(ts_nanos_micros) == "1970-01-01 00:00:00.000001200"\n\n def test_repr_matches_pydatetime_tz_pytz(self):\n dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc)\n assert str(dt_date) == str(Timestamp(dt_date))\n\n dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=pytz.utc)\n assert str(dt_datetime) == str(Timestamp(dt_datetime))\n\n dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=pytz.utc)\n assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))\n\n def test_repr_matches_pydatetime_tz_dateutil(self):\n utc = dateutil.tz.tzutc()\n\n dt_date = datetime(2013, 1, 2, tzinfo=utc)\n assert str(dt_date) == str(Timestamp(dt_date))\n\n dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=utc)\n assert str(dt_datetime) == str(Timestamp(dt_datetime))\n\n dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=utc)\n assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_formats.py
test_formats.py
Python
6,864
0.95
0.059701
0.028736
node-utils
940
2024-01-13T22:44:53.408437
BSD-3-Clause
true
d2d483d3c60520363ba27e3319b3d4eb
""" test the scalar Timestamp """\n\nimport calendar\nfrom datetime import (\n datetime,\n timedelta,\n timezone,\n)\nimport locale\nimport time\nimport unicodedata\n\nfrom dateutil.tz import (\n tzlocal,\n tzutc,\n)\nfrom hypothesis import (\n given,\n strategies as st,\n)\nimport numpy as np\nimport pytest\nimport pytz\nfrom pytz import utc\n\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas._libs.tslibs.timezones import (\n dateutil_gettz as gettz,\n get_timezone,\n maybe_get_tz,\n tz_compare,\n)\nfrom pandas.compat import IS64\n\nfrom pandas import (\n NaT,\n Timedelta,\n Timestamp,\n)\nimport pandas._testing as tm\n\nfrom pandas.tseries import offsets\nfrom pandas.tseries.frequencies import to_offset\n\n\nclass TestTimestampProperties:\n def test_properties_business(self):\n freq = to_offset("B")\n\n ts = Timestamp("2017-10-01")\n assert ts.dayofweek == 6\n assert ts.day_of_week == 6\n assert ts.is_month_start # not a weekday\n assert not freq.is_month_start(ts)\n assert freq.is_month_start(ts + Timedelta(days=1))\n assert not freq.is_quarter_start(ts)\n assert freq.is_quarter_start(ts + Timedelta(days=1))\n\n ts = Timestamp("2017-09-30")\n assert ts.dayofweek == 5\n assert ts.day_of_week == 5\n assert ts.is_month_end\n assert not freq.is_month_end(ts)\n assert freq.is_month_end(ts - Timedelta(days=1))\n assert ts.is_quarter_end\n assert not freq.is_quarter_end(ts)\n assert freq.is_quarter_end(ts - Timedelta(days=1))\n\n @pytest.mark.parametrize(\n "attr, expected",\n [\n ["year", 2014],\n ["month", 12],\n ["day", 31],\n ["hour", 23],\n ["minute", 59],\n ["second", 0],\n ["microsecond", 0],\n ["nanosecond", 0],\n ["dayofweek", 2],\n ["day_of_week", 2],\n ["quarter", 4],\n ["dayofyear", 365],\n ["day_of_year", 365],\n ["week", 1],\n ["daysinmonth", 31],\n ],\n )\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n def test_fields(self, attr, expected, tz):\n # GH 10050\n # GH 13303\n ts = Timestamp("2014-12-31 23:59:00", tz=tz)\n result = getattr(ts, attr)\n # that we are int like\n assert isinstance(result, int)\n assert result == expected\n\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n def test_millisecond_raises(self, tz):\n ts = Timestamp("2014-12-31 23:59:00", tz=tz)\n msg = "'Timestamp' object has no attribute 'millisecond'"\n with pytest.raises(AttributeError, match=msg):\n ts.millisecond\n\n @pytest.mark.parametrize(\n "start", ["is_month_start", "is_quarter_start", "is_year_start"]\n )\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n def test_is_start(self, start, tz):\n ts = Timestamp("2014-01-01 00:00:00", tz=tz)\n assert getattr(ts, start)\n\n @pytest.mark.parametrize("end", ["is_month_end", "is_year_end", "is_quarter_end"])\n @pytest.mark.parametrize("tz", [None, "US/Eastern"])\n def test_is_end(self, end, tz):\n ts = Timestamp("2014-12-31 23:59:59", tz=tz)\n assert getattr(ts, end)\n\n # GH 12806\n @pytest.mark.parametrize(\n "data",\n [Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")],\n )\n # error: Unsupported operand types for + ("List[None]" and "List[str]")\n @pytest.mark.parametrize(\n "time_locale", [None] + tm.get_locales() # type: ignore[operator]\n )\n def test_names(self, data, time_locale):\n # GH 17354\n # Test .day_name(), .month_name\n if time_locale is None:\n expected_day = "Monday"\n expected_month = "August"\n else:\n with tm.set_locale(time_locale, locale.LC_TIME):\n expected_day = calendar.day_name[0].capitalize()\n expected_month = calendar.month_name[8].capitalize()\n\n result_day = data.day_name(time_locale)\n result_month = data.month_name(time_locale)\n\n # Work around https://github.com/pandas-dev/pandas/issues/22342\n # different normalizations\n expected_day = unicodedata.normalize("NFD", expected_day)\n expected_month = unicodedata.normalize("NFD", expected_month)\n\n result_day = unicodedata.normalize("NFD", result_day)\n result_month = unicodedata.normalize("NFD", result_month)\n\n assert result_day == expected_day\n assert result_month == expected_month\n\n # Test NaT\n nan_ts = Timestamp(NaT)\n assert np.isnan(nan_ts.day_name(time_locale))\n assert np.isnan(nan_ts.month_name(time_locale))\n\n def test_is_leap_year(self, tz_naive_fixture):\n tz = tz_naive_fixture\n if not IS64 and tz == tzlocal():\n # https://github.com/dateutil/dateutil/issues/197\n pytest.skip(\n "tzlocal() on a 32 bit platform causes internal overflow errors"\n )\n # GH 13727\n dt = Timestamp("2000-01-01 00:00:00", tz=tz)\n assert dt.is_leap_year\n assert isinstance(dt.is_leap_year, bool)\n\n dt = Timestamp("1999-01-01 00:00:00", tz=tz)\n assert not dt.is_leap_year\n\n dt = Timestamp("2004-01-01 00:00:00", tz=tz)\n assert dt.is_leap_year\n\n dt = Timestamp("2100-01-01 00:00:00", tz=tz)\n assert not dt.is_leap_year\n\n def test_woy_boundary(self):\n # make sure weeks at year boundaries are correct\n d = datetime(2013, 12, 31)\n result = Timestamp(d).week\n expected = 1 # ISO standard\n assert result == expected\n\n d = datetime(2008, 12, 28)\n result = Timestamp(d).week\n expected = 52 # ISO standard\n assert result == expected\n\n d = datetime(2009, 12, 31)\n result = Timestamp(d).week\n expected = 53 # ISO standard\n assert result == expected\n\n d = datetime(2010, 1, 1)\n result = Timestamp(d).week\n expected = 53 # ISO standard\n assert result == expected\n\n d = datetime(2010, 1, 3)\n result = Timestamp(d).week\n expected = 53 # ISO standard\n assert result == expected\n\n result = np.array(\n [\n Timestamp(datetime(*args)).week\n for args in [(2000, 1, 1), (2000, 1, 2), (2005, 1, 1), (2005, 1, 2)]\n ]\n )\n assert (result == [52, 52, 53, 53]).all()\n\n def test_resolution(self):\n # GH#21336, GH#21365\n dt = Timestamp("2100-01-01 00:00:00.000000000")\n assert dt.resolution == Timedelta(nanoseconds=1)\n\n # Check that the attribute is available on the class, mirroring\n # the stdlib datetime behavior\n assert Timestamp.resolution == Timedelta(nanoseconds=1)\n\n assert dt.as_unit("us").resolution == Timedelta(microseconds=1)\n assert dt.as_unit("ms").resolution == Timedelta(milliseconds=1)\n assert dt.as_unit("s").resolution == Timedelta(seconds=1)\n\n @pytest.mark.parametrize(\n "date_string, expected",\n [\n ("0000-2-29", 1),\n ("0000-3-1", 2),\n ("1582-10-14", 3),\n ("-0040-1-1", 4),\n ("2023-06-18", 6),\n ],\n )\n def test_dow_historic(self, date_string, expected):\n # GH 53738\n ts = Timestamp(date_string)\n dow = ts.weekday()\n assert dow == expected\n\n @given(\n ts=st.datetimes(),\n sign=st.sampled_from(["-", ""]),\n )\n def test_dow_parametric(self, ts, sign):\n # GH 53738\n ts = (\n f"{sign}{str(ts.year).zfill(4)}"\n f"-{str(ts.month).zfill(2)}"\n f"-{str(ts.day).zfill(2)}"\n )\n result = Timestamp(ts).weekday()\n expected = (\n (np.datetime64(ts) - np.datetime64("1970-01-01")).astype("int64") - 4\n ) % 7\n assert result == expected\n\n\nclass TestTimestamp:\n @pytest.mark.parametrize("tz", [None, pytz.timezone("US/Pacific")])\n def test_disallow_setting_tz(self, tz):\n # GH#3746\n ts = Timestamp("2010")\n msg = "Cannot directly set timezone"\n with pytest.raises(AttributeError, match=msg):\n ts.tz = tz\n\n def test_default_to_stdlib_utc(self):\n assert Timestamp.utcnow().tz is timezone.utc\n assert Timestamp.now("UTC").tz is timezone.utc\n assert Timestamp("2016-01-01", tz="UTC").tz is timezone.utc\n\n def test_tz(self):\n tstr = "2014-02-01 09:00"\n ts = Timestamp(tstr)\n local = ts.tz_localize("Asia/Tokyo")\n assert local.hour == 9\n assert local == Timestamp(tstr, tz="Asia/Tokyo")\n conv = local.tz_convert("US/Eastern")\n assert conv == Timestamp("2014-01-31 19:00", tz="US/Eastern")\n assert conv.hour == 19\n\n # preserves nanosecond\n ts = Timestamp(tstr) + offsets.Nano(5)\n local = ts.tz_localize("Asia/Tokyo")\n assert local.hour == 9\n assert local.nanosecond == 5\n conv = local.tz_convert("US/Eastern")\n assert conv.nanosecond == 5\n assert conv.hour == 19\n\n def test_utc_z_designator(self):\n assert get_timezone(Timestamp("2014-11-02 01:00Z").tzinfo) is timezone.utc\n\n def test_asm8(self):\n ns = [Timestamp.min._value, Timestamp.max._value, 1000]\n\n for n in ns:\n assert (\n Timestamp(n).asm8.view("i8") == np.datetime64(n, "ns").view("i8") == n\n )\n\n assert Timestamp("nat").asm8.view("i8") == np.datetime64("nat", "ns").view("i8")\n\n def test_class_ops(self):\n def compare(x, y):\n assert int((Timestamp(x)._value - Timestamp(y)._value) / 1e9) == 0\n\n compare(Timestamp.now(), datetime.now())\n compare(Timestamp.now("UTC"), datetime.now(pytz.timezone("UTC")))\n compare(Timestamp.now("UTC"), datetime.now(tzutc()))\n compare(Timestamp.utcnow(), datetime.now(timezone.utc))\n compare(Timestamp.today(), datetime.today())\n current_time = calendar.timegm(datetime.now().utctimetuple())\n\n ts_utc = Timestamp.utcfromtimestamp(current_time)\n assert ts_utc.timestamp() == current_time\n compare(\n Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)\n )\n compare(\n # Support tz kwarg in Timestamp.fromtimestamp\n Timestamp.fromtimestamp(current_time, "UTC"),\n datetime.fromtimestamp(current_time, utc),\n )\n compare(\n # Support tz kwarg in Timestamp.fromtimestamp\n Timestamp.fromtimestamp(current_time, tz="UTC"),\n datetime.fromtimestamp(current_time, utc),\n )\n\n date_component = datetime.now(timezone.utc)\n time_component = (date_component + timedelta(minutes=10)).time()\n compare(\n Timestamp.combine(date_component, time_component),\n datetime.combine(date_component, time_component),\n )\n\n def test_basics_nanos(self):\n val = np.int64(946_684_800_000_000_000).view("M8[ns]")\n stamp = Timestamp(val.view("i8") + 500)\n assert stamp.year == 2000\n assert stamp.month == 1\n assert stamp.microsecond == 0\n assert stamp.nanosecond == 500\n\n # GH 14415\n val = np.iinfo(np.int64).min + 80_000_000_000_000\n stamp = Timestamp(val)\n assert stamp.year == 1677\n assert stamp.month == 9\n assert stamp.day == 21\n assert stamp.microsecond == 145224\n assert stamp.nanosecond == 192\n\n def test_roundtrip(self):\n # test value to string and back conversions\n # further test accessors\n base = Timestamp("20140101 00:00:00").as_unit("ns")\n\n result = Timestamp(base._value + Timedelta("5ms")._value)\n assert result == Timestamp(f"{base}.005000")\n assert result.microsecond == 5000\n\n result = Timestamp(base._value + Timedelta("5us")._value)\n assert result == Timestamp(f"{base}.000005")\n assert result.microsecond == 5\n\n result = Timestamp(base._value + Timedelta("5ns")._value)\n assert result == Timestamp(f"{base}.000000005")\n assert result.nanosecond == 5\n assert result.microsecond == 0\n\n result = Timestamp(base._value + Timedelta("6ms 5us")._value)\n assert result == Timestamp(f"{base}.006005")\n assert result.microsecond == 5 + 6 * 1000\n\n result = Timestamp(base._value + Timedelta("200ms 5us")._value)\n assert result == Timestamp(f"{base}.200005")\n assert result.microsecond == 5 + 200 * 1000\n\n def test_hash_equivalent(self):\n d = {datetime(2011, 1, 1): 5}\n stamp = Timestamp(datetime(2011, 1, 1))\n assert d[stamp] == 5\n\n @pytest.mark.parametrize(\n "timezone, year, month, day, hour",\n [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]],\n )\n def test_hash_timestamp_with_fold(self, timezone, year, month, day, hour):\n # see gh-33931\n test_timezone = gettz(timezone)\n transition_1 = Timestamp(\n year=year,\n month=month,\n day=day,\n hour=hour,\n minute=0,\n fold=0,\n tzinfo=test_timezone,\n )\n transition_2 = Timestamp(\n year=year,\n month=month,\n day=day,\n hour=hour,\n minute=0,\n fold=1,\n tzinfo=test_timezone,\n )\n assert hash(transition_1) == hash(transition_2)\n\n\nclass TestTimestampNsOperations:\n def test_nanosecond_string_parsing(self):\n ts = Timestamp("2013-05-01 07:15:45.123456789")\n # GH 7878\n expected_repr = "2013-05-01 07:15:45.123456789"\n expected_value = 1_367_392_545_123_456_789\n assert ts._value == expected_value\n assert expected_repr in repr(ts)\n\n ts = Timestamp("2013-05-01 07:15:45.123456789+09:00", tz="Asia/Tokyo")\n assert ts._value == expected_value - 9 * 3600 * 1_000_000_000\n assert expected_repr in repr(ts)\n\n ts = Timestamp("2013-05-01 07:15:45.123456789", tz="UTC")\n assert ts._value == expected_value\n assert expected_repr in repr(ts)\n\n ts = Timestamp("2013-05-01 07:15:45.123456789", tz="US/Eastern")\n assert ts._value == expected_value + 4 * 3600 * 1_000_000_000\n assert expected_repr in repr(ts)\n\n # GH 10041\n ts = Timestamp("20130501T071545.123456789")\n assert ts._value == expected_value\n assert expected_repr in repr(ts)\n\n def test_nanosecond_timestamp(self):\n # GH 7610\n expected = 1_293_840_000_000_000_005\n t = Timestamp("2011-01-01") + offsets.Nano(5)\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"\n assert t._value == expected\n assert t.nanosecond == 5\n\n t = Timestamp(t)\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"\n assert t._value == expected\n assert t.nanosecond == 5\n\n t = Timestamp("2011-01-01 00:00:00.000000005")\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"\n assert t._value == expected\n assert t.nanosecond == 5\n\n expected = 1_293_840_000_000_000_010\n t = t + offsets.Nano(5)\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"\n assert t._value == expected\n assert t.nanosecond == 10\n\n t = Timestamp(t)\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"\n assert t._value == expected\n assert t.nanosecond == 10\n\n t = Timestamp("2011-01-01 00:00:00.000000010")\n assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"\n assert t._value == expected\n assert t.nanosecond == 10\n\n\nclass TestTimestampConversion:\n def test_conversion(self):\n # GH#9255\n ts = Timestamp("2000-01-01").as_unit("ns")\n\n result = ts.to_pydatetime()\n expected = datetime(2000, 1, 1)\n assert result == expected\n assert type(result) == type(expected)\n\n result = ts.to_datetime64()\n expected = np.datetime64(ts._value, "ns")\n assert result == expected\n assert type(result) == type(expected)\n assert result.dtype == expected.dtype\n\n def test_to_period_tz_warning(self):\n # GH#21333 make sure a warning is issued when timezone\n # info is lost\n ts = Timestamp("2009-04-15 16:17:18", tz="US/Eastern")\n with tm.assert_produces_warning(UserWarning):\n # warning that timezone info will be lost\n ts.to_period("D")\n\n def test_to_numpy_alias(self):\n # GH 24653: alias .to_numpy() for scalars\n ts = Timestamp(datetime.now())\n assert ts.to_datetime64() == ts.to_numpy()\n\n # GH#44460\n msg = "dtype and copy arguments are ignored"\n with pytest.raises(ValueError, match=msg):\n ts.to_numpy("M8[s]")\n with pytest.raises(ValueError, match=msg):\n ts.to_numpy(copy=True)\n\n\nclass TestNonNano:\n @pytest.fixture(params=["s", "ms", "us"])\n def reso(self, request):\n return request.param\n\n @pytest.fixture\n def dt64(self, reso):\n # cases that are in-bounds for nanosecond, so we can compare against\n # the existing implementation.\n return np.datetime64("2016-01-01", reso)\n\n @pytest.fixture\n def ts(self, dt64):\n return Timestamp._from_dt64(dt64)\n\n @pytest.fixture\n def ts_tz(self, ts, tz_aware_fixture):\n tz = maybe_get_tz(tz_aware_fixture)\n return Timestamp._from_value_and_reso(ts._value, ts._creso, tz)\n\n def test_non_nano_construction(self, dt64, ts, reso):\n assert ts._value == dt64.view("i8")\n\n if reso == "s":\n assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value\n elif reso == "ms":\n assert ts._creso == NpyDatetimeUnit.NPY_FR_ms.value\n elif reso == "us":\n assert ts._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n def test_non_nano_fields(self, dt64, ts):\n alt = Timestamp(dt64)\n\n assert ts.year == alt.year\n assert ts.month == alt.month\n assert ts.day == alt.day\n assert ts.hour == ts.minute == ts.second == ts.microsecond == 0\n assert ts.nanosecond == 0\n\n assert ts.to_julian_date() == alt.to_julian_date()\n assert ts.weekday() == alt.weekday()\n assert ts.isoweekday() == alt.isoweekday()\n\n def test_start_end_fields(self, ts):\n assert ts.is_year_start\n assert ts.is_quarter_start\n assert ts.is_month_start\n assert not ts.is_year_end\n assert not ts.is_month_end\n assert not ts.is_month_end\n\n # 2016-01-01 is a Friday, so is year/quarter/month start with this freq\n assert ts.is_year_start\n assert ts.is_quarter_start\n assert ts.is_month_start\n assert not ts.is_year_end\n assert not ts.is_month_end\n assert not ts.is_month_end\n\n def test_day_name(self, dt64, ts):\n alt = Timestamp(dt64)\n assert ts.day_name() == alt.day_name()\n\n def test_month_name(self, dt64, ts):\n alt = Timestamp(dt64)\n assert ts.month_name() == alt.month_name()\n\n def test_tz_convert(self, ts):\n ts = Timestamp._from_value_and_reso(ts._value, ts._creso, utc)\n\n tz = pytz.timezone("US/Pacific")\n result = ts.tz_convert(tz)\n\n assert isinstance(result, Timestamp)\n assert result._creso == ts._creso\n assert tz_compare(result.tz, tz)\n\n def test_repr(self, dt64, ts):\n alt = Timestamp(dt64)\n\n assert str(ts) == str(alt)\n assert repr(ts) == repr(alt)\n\n def test_comparison(self, dt64, ts):\n alt = Timestamp(dt64)\n\n assert ts == dt64\n assert dt64 == ts\n assert ts == alt\n assert alt == ts\n\n assert not ts != dt64\n assert not dt64 != ts\n assert not ts != alt\n assert not alt != ts\n\n assert not ts < dt64\n assert not dt64 < ts\n assert not ts < alt\n assert not alt < ts\n\n assert not ts > dt64\n assert not dt64 > ts\n assert not ts > alt\n assert not alt > ts\n\n assert ts >= dt64\n assert dt64 >= ts\n assert ts >= alt\n assert alt >= ts\n\n assert ts <= dt64\n assert dt64 <= ts\n assert ts <= alt\n assert alt <= ts\n\n def test_cmp_cross_reso(self):\n # numpy gets this wrong because of silent overflow\n dt64 = np.datetime64(9223372800, "s") # won't fit in M8[ns]\n ts = Timestamp._from_dt64(dt64)\n\n # subtracting 3600*24 gives a datetime64 that _can_ fit inside the\n # nanosecond implementation bounds.\n other = Timestamp(dt64 - 3600 * 24).as_unit("ns")\n assert other < ts\n assert other.asm8 > ts.asm8 # <- numpy gets this wrong\n assert ts > other\n assert ts.asm8 < other.asm8 # <- numpy gets this wrong\n assert not other == ts\n assert ts != other\n\n @pytest.mark.xfail(reason="Dispatches to np.datetime64 which is wrong")\n def test_cmp_cross_reso_reversed_dt64(self):\n dt64 = np.datetime64(106752, "D") # won't fit in M8[ns]\n ts = Timestamp._from_dt64(dt64)\n other = Timestamp(dt64 - 1)\n\n assert other.asm8 < ts\n\n def test_pickle(self, ts, tz_aware_fixture):\n tz = tz_aware_fixture\n tz = maybe_get_tz(tz)\n ts = Timestamp._from_value_and_reso(ts._value, ts._creso, tz)\n rt = tm.round_trip_pickle(ts)\n assert rt._creso == ts._creso\n assert rt == ts\n\n def test_normalize(self, dt64, ts):\n alt = Timestamp(dt64)\n result = ts.normalize()\n assert result._creso == ts._creso\n assert result == alt.normalize()\n\n def test_asm8(self, dt64, ts):\n rt = ts.asm8\n assert rt == dt64\n assert rt.dtype == dt64.dtype\n\n def test_to_numpy(self, dt64, ts):\n res = ts.to_numpy()\n assert res == dt64\n assert res.dtype == dt64.dtype\n\n def test_to_datetime64(self, dt64, ts):\n res = ts.to_datetime64()\n assert res == dt64\n assert res.dtype == dt64.dtype\n\n def test_timestamp(self, dt64, ts):\n alt = Timestamp(dt64)\n assert ts.timestamp() == alt.timestamp()\n\n def test_to_period(self, dt64, ts):\n alt = Timestamp(dt64)\n assert ts.to_period("D") == alt.to_period("D")\n\n @pytest.mark.parametrize(\n "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")]\n )\n def test_addsub_timedeltalike_non_nano(self, dt64, ts, td):\n exp_reso = max(ts._creso, Timedelta(td)._creso)\n\n result = ts - td\n expected = Timestamp(dt64) - td\n assert isinstance(result, Timestamp)\n assert result._creso == exp_reso\n assert result == expected\n\n result = ts + td\n expected = Timestamp(dt64) + td\n assert isinstance(result, Timestamp)\n assert result._creso == exp_reso\n assert result == expected\n\n result = td + ts\n expected = td + Timestamp(dt64)\n assert isinstance(result, Timestamp)\n assert result._creso == exp_reso\n assert result == expected\n\n def test_addsub_offset(self, ts_tz):\n # specifically non-Tick offset\n off = offsets.YearEnd(1)\n result = ts_tz + off\n\n assert isinstance(result, Timestamp)\n assert result._creso == ts_tz._creso\n if ts_tz.month == 12 and ts_tz.day == 31:\n assert result.year == ts_tz.year + 1\n else:\n assert result.year == ts_tz.year\n assert result.day == 31\n assert result.month == 12\n assert tz_compare(result.tz, ts_tz.tz)\n\n result = ts_tz - off\n\n assert isinstance(result, Timestamp)\n assert result._creso == ts_tz._creso\n assert result.year == ts_tz.year - 1\n assert result.day == 31\n assert result.month == 12\n assert tz_compare(result.tz, ts_tz.tz)\n\n def test_sub_datetimelike_mismatched_reso(self, ts_tz):\n # case with non-lossy rounding\n ts = ts_tz\n\n # choose a unit for `other` that doesn't match ts_tz's;\n # this construction ensures we get cases with other._creso < ts._creso\n # and cases with other._creso > ts._creso\n unit = {\n NpyDatetimeUnit.NPY_FR_us.value: "ms",\n NpyDatetimeUnit.NPY_FR_ms.value: "s",\n NpyDatetimeUnit.NPY_FR_s.value: "us",\n }[ts._creso]\n other = ts.as_unit(unit)\n assert other._creso != ts._creso\n\n result = ts - other\n assert isinstance(result, Timedelta)\n assert result._value == 0\n assert result._creso == max(ts._creso, other._creso)\n\n result = other - ts\n assert isinstance(result, Timedelta)\n assert result._value == 0\n assert result._creso == max(ts._creso, other._creso)\n\n if ts._creso < other._creso:\n # Case where rounding is lossy\n other2 = other + Timedelta._from_value_and_reso(1, other._creso)\n exp = ts.as_unit(other.unit) - other2\n\n res = ts - other2\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n\n res = other2 - ts\n assert res == -exp\n assert res._creso == max(ts._creso, other._creso)\n else:\n ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)\n exp = ts2 - other.as_unit(ts2.unit)\n\n res = ts2 - other\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n res = other - ts2\n assert res == -exp\n assert res._creso == max(ts._creso, other._creso)\n\n def test_sub_timedeltalike_mismatched_reso(self, ts_tz):\n # case with non-lossy rounding\n ts = ts_tz\n\n # choose a unit for `other` that doesn't match ts_tz's;\n # this construction ensures we get cases with other._creso < ts._creso\n # and cases with other._creso > ts._creso\n unit = {\n NpyDatetimeUnit.NPY_FR_us.value: "ms",\n NpyDatetimeUnit.NPY_FR_ms.value: "s",\n NpyDatetimeUnit.NPY_FR_s.value: "us",\n }[ts._creso]\n other = Timedelta(0).as_unit(unit)\n assert other._creso != ts._creso\n\n result = ts + other\n assert isinstance(result, Timestamp)\n assert result == ts\n assert result._creso == max(ts._creso, other._creso)\n\n result = other + ts\n assert isinstance(result, Timestamp)\n assert result == ts\n assert result._creso == max(ts._creso, other._creso)\n\n if ts._creso < other._creso:\n # Case where rounding is lossy\n other2 = other + Timedelta._from_value_and_reso(1, other._creso)\n exp = ts.as_unit(other.unit) + other2\n res = ts + other2\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n res = other2 + ts\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n else:\n ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)\n exp = ts2 + other.as_unit(ts2.unit)\n\n res = ts2 + other\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n res = other + ts2\n assert res == exp\n assert res._creso == max(ts._creso, other._creso)\n\n def test_addition_doesnt_downcast_reso(self):\n # https://github.com/pandas-dev/pandas/pull/48748#pullrequestreview-1122635413\n ts = Timestamp(year=2022, month=1, day=1, microsecond=999999).as_unit("us")\n td = Timedelta(microseconds=1).as_unit("us")\n res = ts + td\n assert res._creso == ts._creso\n\n def test_sub_timedelta64_mismatched_reso(self, ts_tz):\n ts = ts_tz\n\n res = ts + np.timedelta64(1, "ns")\n exp = ts.as_unit("ns") + np.timedelta64(1, "ns")\n assert exp == res\n assert exp._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n def test_min(self, ts):\n assert ts.min <= ts\n assert ts.min._creso == ts._creso\n assert ts.min._value == NaT._value + 1\n\n def test_max(self, ts):\n assert ts.max >= ts\n assert ts.max._creso == ts._creso\n assert ts.max._value == np.iinfo(np.int64).max\n\n def test_resolution(self, ts):\n expected = Timedelta._from_value_and_reso(1, ts._creso)\n result = ts.resolution\n assert result == expected\n assert result._creso == expected._creso\n\n def test_out_of_ns_bounds(self):\n # https://github.com/pandas-dev/pandas/issues/51060\n result = Timestamp(-52700112000, unit="s")\n assert result == Timestamp("0300-01-01")\n assert result.to_numpy() == np.datetime64("0300-01-01T00:00:00", "s")\n\n\ndef test_timestamp_class_min_max_resolution():\n # when accessed on the class (as opposed to an instance), we default\n # to nanoseconds\n assert Timestamp.min == Timestamp(NaT._value + 1)\n assert Timestamp.min._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n assert Timestamp.max == Timestamp(np.iinfo(np.int64).max)\n assert Timestamp.max._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n assert Timestamp.resolution == Timedelta(1)\n assert Timestamp.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value\n\n\ndef test_delimited_date():\n # https://github.com/pandas-dev/pandas/issues/50231\n with tm.assert_produces_warning(None):\n result = Timestamp("13-01-2000")\n expected = Timestamp(2000, 1, 13)\n assert result == expected\n\n\ndef test_utctimetuple():\n # GH 32174\n ts = Timestamp("2000-01-01", tz="UTC")\n result = ts.utctimetuple()\n expected = time.struct_time((2000, 1, 1, 0, 0, 0, 5, 1, 0))\n assert result == expected\n\n\ndef test_negative_dates():\n # https://github.com/pandas-dev/pandas/issues/50787\n ts = Timestamp("-2000-01-01")\n msg = (\n " not yet supported on Timestamps which are outside the range of "\n "Python's standard library. For now, please call the components you need "\n r"\(such as `.year` and `.month`\) and construct your string from there.$"\n )\n func = "^strftime"\n with pytest.raises(NotImplementedError, match=func + msg):\n ts.strftime("%Y")\n\n msg = (\n " not yet supported on Timestamps which "\n "are outside the range of Python's standard library. "\n )\n func = "^date"\n with pytest.raises(NotImplementedError, match=func + msg):\n ts.date()\n func = "^isocalendar"\n with pytest.raises(NotImplementedError, match=func + msg):\n ts.isocalendar()\n func = "^timetuple"\n with pytest.raises(NotImplementedError, match=func + msg):\n ts.timetuple()\n func = "^toordinal"\n with pytest.raises(NotImplementedError, match=func + msg):\n ts.toordinal()\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_timestamp.py
test_timestamp.py
Python
31,042
0.95
0.088362
0.076129
react-lib
311
2023-11-07T13:52:36.945477
Apache-2.0
true
edfa293e0a2f3c96f4aa683e2a252a51
"""\nTests for Timestamp timezone-related methods\n"""\nfrom datetime import datetime\n\nfrom pandas._libs.tslibs import timezones\n\nfrom pandas import Timestamp\n\n\nclass TestTimestampTZOperations:\n # ------------------------------------------------------------------\n\n def test_timestamp_timetz_equivalent_with_datetime_tz(self, tz_naive_fixture):\n # GH21358\n tz = timezones.maybe_get_tz(tz_naive_fixture)\n\n stamp = Timestamp("2018-06-04 10:20:30", tz=tz)\n _datetime = datetime(2018, 6, 4, hour=10, minute=20, second=30, tzinfo=tz)\n\n result = stamp.timetz()\n expected = _datetime.timetz()\n\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\test_timezones.py
test_timezones.py
Python
666
0.95
0.125
0.125
node-utils
211
2024-01-10T01:50:44.992597
GPL-3.0
true
f8fe4641afc4d1f347fa4a6ce96b5b2c
import pytest\n\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas.errors import OutOfBoundsDatetime\n\nfrom pandas import Timestamp\n\n\nclass TestTimestampAsUnit:\n def test_as_unit(self):\n ts = Timestamp("1970-01-01").as_unit("ns")\n assert ts.unit == "ns"\n\n assert ts.as_unit("ns") is ts\n\n res = ts.as_unit("us")\n assert res._value == ts._value // 1000\n assert res._creso == NpyDatetimeUnit.NPY_FR_us.value\n\n rt = res.as_unit("ns")\n assert rt._value == ts._value\n assert rt._creso == ts._creso\n\n res = ts.as_unit("ms")\n assert res._value == ts._value // 1_000_000\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n rt = res.as_unit("ns")\n assert rt._value == ts._value\n assert rt._creso == ts._creso\n\n res = ts.as_unit("s")\n assert res._value == ts._value // 1_000_000_000\n assert res._creso == NpyDatetimeUnit.NPY_FR_s.value\n\n rt = res.as_unit("ns")\n assert rt._value == ts._value\n assert rt._creso == ts._creso\n\n def test_as_unit_overflows(self):\n # microsecond that would be just out of bounds for nano\n us = 9223372800000000\n ts = Timestamp._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value, None)\n\n msg = "Cannot cast 2262-04-12 00:00:00 to unit='ns' without overflow"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n ts.as_unit("ns")\n\n res = ts.as_unit("ms")\n assert res._value == us // 1000\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n\n def test_as_unit_rounding(self):\n ts = Timestamp(1_500_000) # i.e. 1500 microseconds\n res = ts.as_unit("ms")\n\n expected = Timestamp(1_000_000) # i.e. 1 millisecond\n assert res == expected\n\n assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value\n assert res._value == 1\n\n with pytest.raises(ValueError, match="Cannot losslessly convert units"):\n ts.as_unit("ms", round_ok=False)\n\n def test_as_unit_non_nano(self):\n # case where we are going neither to nor from nano\n ts = Timestamp("1970-01-02").as_unit("ms")\n assert ts.year == 1970\n assert ts.month == 1\n assert ts.day == 2\n assert ts.hour == ts.minute == ts.second == ts.microsecond == ts.nanosecond == 0\n\n res = ts.as_unit("s")\n assert res._value == 24 * 3600\n assert res.year == 1970\n assert res.month == 1\n assert res.day == 2\n assert (\n res.hour\n == res.minute\n == res.second\n == res.microsecond\n == res.nanosecond\n == 0\n )\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_as_unit.py
test_as_unit.py
Python
2,706
0.95
0.069767
0.030303
awesome-app
536
2025-05-04T23:55:02.161247
GPL-3.0
true
c6eb9019828272946ed11d16dde967d3
import pytest\n\nfrom pandas._libs.tslibs import Timestamp\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\n\n\nclass TestTimestampNormalize:\n @pytest.mark.parametrize("arg", ["2013-11-30", "2013-11-30 12:00:00"])\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_normalize(self, tz_naive_fixture, arg, unit):\n tz = tz_naive_fixture\n ts = Timestamp(arg, tz=tz).as_unit(unit)\n result = ts.normalize()\n expected = Timestamp("2013-11-30", tz=tz)\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n def test_normalize_pre_epoch_dates(self):\n # GH: 36294\n result = Timestamp("1969-01-01 09:00:00").normalize()\n expected = Timestamp("1969-01-01 00:00:00")\n assert result == expected\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_normalize.py
test_normalize.py
Python
831
0.95
0.136364
0.055556
react-lib
257
2023-10-27T08:42:43.328035
GPL-3.0
true
e413183cfe958f4a06c70559ed4572f1
from datetime import datetime\n\nfrom dateutil.tz import gettz\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import (\n OutOfBoundsDatetime,\n Timestamp,\n conversion,\n)\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nimport pandas.util._test_decorators as td\n\nimport pandas._testing as tm\n\n\nclass TestTimestampReplace:\n def test_replace_out_of_pydatetime_bounds(self):\n # GH#50348\n ts = Timestamp("2016-01-01").as_unit("ns")\n\n msg = "Out of bounds timestamp: 99999-01-01 00:00:00 with frequency 'ns'"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n ts.replace(year=99_999)\n\n ts = ts.as_unit("ms")\n result = ts.replace(year=99_999)\n assert result.year == 99_999\n assert result._value == Timestamp(np.datetime64("99999-01-01", "ms"))._value\n\n def test_replace_non_nano(self):\n ts = Timestamp._from_value_and_reso(\n 91514880000000000, NpyDatetimeUnit.NPY_FR_us.value, None\n )\n assert ts.to_pydatetime() == datetime(4869, 12, 28)\n\n result = ts.replace(year=4900)\n assert result._creso == ts._creso\n assert result.to_pydatetime() == datetime(4900, 12, 28)\n\n def test_replace_naive(self):\n # GH#14621, GH#7825\n ts = Timestamp("2016-01-01 09:00:00")\n result = ts.replace(hour=0)\n expected = Timestamp("2016-01-01 00:00:00")\n assert result == expected\n\n def test_replace_aware(self, tz_aware_fixture):\n tz = tz_aware_fixture\n # GH#14621, GH#7825\n # replacing datetime components with and w/o presence of a timezone\n ts = Timestamp("2016-01-01 09:00:00", tz=tz)\n result = ts.replace(hour=0)\n expected = Timestamp("2016-01-01 00:00:00", tz=tz)\n assert result == expected\n\n def test_replace_preserves_nanos(self, tz_aware_fixture):\n tz = tz_aware_fixture\n # GH#14621, GH#7825\n ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)\n result = ts.replace(hour=0)\n expected = Timestamp("2016-01-01 00:00:00.000000123", tz=tz)\n assert result == expected\n\n def test_replace_multiple(self, tz_aware_fixture):\n tz = tz_aware_fixture\n # GH#14621, GH#7825\n # replacing datetime components with and w/o presence of a timezone\n # test all\n ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)\n result = ts.replace(\n year=2015,\n month=2,\n day=2,\n hour=0,\n minute=5,\n second=5,\n microsecond=5,\n nanosecond=5,\n )\n expected = Timestamp("2015-02-02 00:05:05.000005005", tz=tz)\n assert result == expected\n\n def test_replace_invalid_kwarg(self, tz_aware_fixture):\n tz = tz_aware_fixture\n # GH#14621, GH#7825\n ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)\n msg = r"replace\(\) got an unexpected keyword argument"\n with pytest.raises(TypeError, match=msg):\n ts.replace(foo=5)\n\n def test_replace_integer_args(self, tz_aware_fixture):\n tz = tz_aware_fixture\n # GH#14621, GH#7825\n ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)\n msg = "value must be an integer, received <class 'float'> for hour"\n with pytest.raises(ValueError, match=msg):\n ts.replace(hour=0.1)\n\n def test_replace_tzinfo_equiv_tz_localize_none(self):\n # GH#14621, GH#7825\n # assert conversion to naive is the same as replacing tzinfo with None\n ts = Timestamp("2013-11-03 01:59:59.999999-0400", tz="US/Eastern")\n assert ts.tz_localize(None) == ts.replace(tzinfo=None)\n\n @td.skip_if_windows\n def test_replace_tzinfo(self):\n # GH#15683\n dt = datetime(2016, 3, 27, 1)\n tzinfo = pytz.timezone("CET").localize(dt, is_dst=False).tzinfo\n\n result_dt = dt.replace(tzinfo=tzinfo)\n result_pd = Timestamp(dt).replace(tzinfo=tzinfo)\n\n # datetime.timestamp() converts in the local timezone\n with tm.set_timezone("UTC"):\n assert result_dt.timestamp() == result_pd.timestamp()\n\n assert result_dt == result_pd\n assert result_dt == result_pd.to_pydatetime()\n\n result_dt = dt.replace(tzinfo=tzinfo).replace(tzinfo=None)\n result_pd = Timestamp(dt).replace(tzinfo=tzinfo).replace(tzinfo=None)\n\n # datetime.timestamp() converts in the local timezone\n with tm.set_timezone("UTC"):\n assert result_dt.timestamp() == result_pd.timestamp()\n\n assert result_dt == result_pd\n assert result_dt == result_pd.to_pydatetime()\n\n @pytest.mark.parametrize(\n "tz, normalize",\n [\n (pytz.timezone("US/Eastern"), lambda x: x.tzinfo.normalize(x)),\n (gettz("US/Eastern"), lambda x: x),\n ],\n )\n def test_replace_across_dst(self, tz, normalize):\n # GH#18319 check that 1) timezone is correctly normalized and\n # 2) that hour is not incorrectly changed by this normalization\n ts_naive = Timestamp("2017-12-03 16:03:30")\n ts_aware = conversion.localize_pydatetime(ts_naive, tz)\n\n # Preliminary sanity-check\n assert ts_aware == normalize(ts_aware)\n\n # Replace across DST boundary\n ts2 = ts_aware.replace(month=6)\n\n # Check that `replace` preserves hour literal\n assert (ts2.hour, ts2.minute) == (ts_aware.hour, ts_aware.minute)\n\n # Check that post-replace object is appropriately normalized\n ts2b = normalize(ts2)\n assert ts2 == ts2b\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_replace_dst_border(self, unit):\n # Gh 7825\n t = Timestamp("2013-11-3", tz="America/Chicago").as_unit(unit)\n result = t.replace(hour=3)\n expected = Timestamp("2013-11-3 03:00:00", tz="America/Chicago")\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n @pytest.mark.parametrize("fold", [0, 1])\n @pytest.mark.parametrize("tz", ["dateutil/Europe/London", "Europe/London"])\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_replace_dst_fold(self, fold, tz, unit):\n # GH 25017\n d = datetime(2019, 10, 27, 2, 30)\n ts = Timestamp(d, tz=tz).as_unit(unit)\n result = ts.replace(hour=1, fold=fold)\n expected = Timestamp(datetime(2019, 10, 27, 1, 30)).tz_localize(\n tz, ambiguous=not fold\n )\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n @pytest.mark.parametrize("fold", [0, 1])\n def test_replace_preserves_fold(self, fold):\n # GH#37610. Check that replace preserves Timestamp fold property\n tz = gettz("Europe/Moscow")\n\n ts = Timestamp(\n year=2009, month=10, day=25, hour=2, minute=30, fold=fold, tzinfo=tz\n )\n ts_replaced = ts.replace(second=1)\n\n assert ts_replaced.fold == fold\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_replace.py
test_replace.py
Python
7,055
0.95
0.088083
0.15
react-lib
89
2024-07-15T21:44:21.334449
BSD-3-Clause
true
cd7727449c047539c08421ad0cb19d3a
from hypothesis import (\n given,\n strategies as st,\n)\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs import lib\nfrom pandas._libs.tslibs import (\n NaT,\n OutOfBoundsDatetime,\n Timedelta,\n Timestamp,\n iNaT,\n to_offset,\n)\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\n\nimport pandas._testing as tm\n\n\nclass TestTimestampRound:\n def test_round_division_by_zero_raises(self):\n ts = Timestamp("2016-01-01")\n\n msg = "Division by zero in rounding"\n with pytest.raises(ValueError, match=msg):\n ts.round("0ns")\n\n @pytest.mark.parametrize(\n "timestamp, freq, expected",\n [\n ("20130101 09:10:11", "D", "20130101"),\n ("20130101 19:10:11", "D", "20130102"),\n ("20130201 12:00:00", "D", "20130202"),\n ("20130104 12:00:00", "D", "20130105"),\n ("2000-01-05 05:09:15.13", "D", "2000-01-05 00:00:00"),\n ("2000-01-05 05:09:15.13", "h", "2000-01-05 05:00:00"),\n ("2000-01-05 05:09:15.13", "s", "2000-01-05 05:09:15"),\n ],\n )\n def test_round_frequencies(self, timestamp, freq, expected):\n dt = Timestamp(timestamp)\n result = dt.round(freq)\n expected = Timestamp(expected)\n assert result == expected\n\n def test_round_tzaware(self):\n dt = Timestamp("20130101 09:10:11", tz="US/Eastern")\n result = dt.round("D")\n expected = Timestamp("20130101", tz="US/Eastern")\n assert result == expected\n\n dt = Timestamp("20130101 09:10:11", tz="US/Eastern")\n result = dt.round("s")\n assert result == dt\n\n def test_round_30min(self):\n # round\n dt = Timestamp("20130104 12:32:00")\n result = dt.round("30Min")\n expected = Timestamp("20130104 12:30:00")\n assert result == expected\n\n def test_round_subsecond(self):\n # GH#14440 & GH#15578\n result = Timestamp("2016-10-17 12:00:00.0015").round("ms")\n expected = Timestamp("2016-10-17 12:00:00.002000")\n assert result == expected\n\n result = Timestamp("2016-10-17 12:00:00.00149").round("ms")\n expected = Timestamp("2016-10-17 12:00:00.001000")\n assert result == expected\n\n ts = Timestamp("2016-10-17 12:00:00.0015")\n for freq in ["us", "ns"]:\n assert ts == ts.round(freq)\n\n result = Timestamp("2016-10-17 12:00:00.001501031").round("10ns")\n expected = Timestamp("2016-10-17 12:00:00.001501030")\n assert result == expected\n\n def test_round_nonstandard_freq(self):\n with tm.assert_produces_warning(False):\n Timestamp("2016-10-17 12:00:00.001501031").round("1010ns")\n\n def test_round_invalid_arg(self):\n stamp = Timestamp("2000-01-05 05:09:15.13")\n with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):\n stamp.round("foo")\n\n @pytest.mark.parametrize(\n "test_input, rounder, freq, expected",\n [\n ("2117-01-01 00:00:45", "floor", "15s", "2117-01-01 00:00:45"),\n ("2117-01-01 00:00:45", "ceil", "15s", "2117-01-01 00:00:45"),\n (\n "2117-01-01 00:00:45.000000012",\n "floor",\n "10ns",\n "2117-01-01 00:00:45.000000010",\n ),\n (\n "1823-01-01 00:00:01.000000012",\n "ceil",\n "10ns",\n "1823-01-01 00:00:01.000000020",\n ),\n ("1823-01-01 00:00:01", "floor", "1s", "1823-01-01 00:00:01"),\n ("1823-01-01 00:00:01", "ceil", "1s", "1823-01-01 00:00:01"),\n ("NaT", "floor", "1s", "NaT"),\n ("NaT", "ceil", "1s", "NaT"),\n ],\n )\n def test_ceil_floor_edge(self, test_input, rounder, freq, expected):\n dt = Timestamp(test_input)\n func = getattr(dt, rounder)\n result = func(freq)\n\n if dt is NaT:\n assert result is NaT\n else:\n expected = Timestamp(expected)\n assert result == expected\n\n @pytest.mark.parametrize(\n "test_input, freq, expected",\n [\n ("2018-01-01 00:02:06", "2s", "2018-01-01 00:02:06"),\n ("2018-01-01 00:02:00", "2min", "2018-01-01 00:02:00"),\n ("2018-01-01 00:04:00", "4min", "2018-01-01 00:04:00"),\n ("2018-01-01 00:15:00", "15min", "2018-01-01 00:15:00"),\n ("2018-01-01 00:20:00", "20min", "2018-01-01 00:20:00"),\n ("2018-01-01 03:00:00", "3h", "2018-01-01 03:00:00"),\n ],\n )\n @pytest.mark.parametrize("rounder", ["ceil", "floor", "round"])\n def test_round_minute_freq(self, test_input, freq, expected, rounder):\n # Ensure timestamps that shouldn't round dont!\n # GH#21262\n\n dt = Timestamp(test_input)\n expected = Timestamp(expected)\n func = getattr(dt, rounder)\n result = func(freq)\n assert result == expected\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_ceil(self, unit):\n dt = Timestamp("20130101 09:10:11").as_unit(unit)\n result = dt.ceil("D")\n expected = Timestamp("20130102")\n assert result == expected\n assert result._creso == dt._creso\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_floor(self, unit):\n dt = Timestamp("20130101 09:10:11").as_unit(unit)\n result = dt.floor("D")\n expected = Timestamp("20130101")\n assert result == expected\n assert result._creso == dt._creso\n\n @pytest.mark.parametrize("method", ["ceil", "round", "floor"])\n @pytest.mark.parametrize(\n "unit",\n ["ns", "us", "ms", "s"],\n )\n def test_round_dst_border_ambiguous(self, method, unit):\n # GH 18946 round near "fall back" DST\n ts = Timestamp("2017-10-29 00:00:00", tz="UTC").tz_convert("Europe/Madrid")\n ts = ts.as_unit(unit)\n #\n result = getattr(ts, method)("h", ambiguous=True)\n assert result == ts\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n result = getattr(ts, method)("h", ambiguous=False)\n expected = Timestamp("2017-10-29 01:00:00", tz="UTC").tz_convert(\n "Europe/Madrid"\n )\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n result = getattr(ts, method)("h", ambiguous="NaT")\n assert result is NaT\n\n msg = "Cannot infer dst time"\n with pytest.raises(pytz.AmbiguousTimeError, match=msg):\n getattr(ts, method)("h", ambiguous="raise")\n\n @pytest.mark.parametrize(\n "method, ts_str, freq",\n [\n ["ceil", "2018-03-11 01:59:00-0600", "5min"],\n ["round", "2018-03-11 01:59:00-0600", "5min"],\n ["floor", "2018-03-11 03:01:00-0500", "2h"],\n ],\n )\n @pytest.mark.parametrize(\n "unit",\n ["ns", "us", "ms", "s"],\n )\n def test_round_dst_border_nonexistent(self, method, ts_str, freq, unit):\n # GH 23324 round near "spring forward" DST\n ts = Timestamp(ts_str, tz="America/Chicago").as_unit(unit)\n result = getattr(ts, method)(freq, nonexistent="shift_forward")\n expected = Timestamp("2018-03-11 03:00:00", tz="America/Chicago")\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n result = getattr(ts, method)(freq, nonexistent="NaT")\n assert result is NaT\n\n msg = "2018-03-11 02:00:00"\n with pytest.raises(pytz.NonExistentTimeError, match=msg):\n getattr(ts, method)(freq, nonexistent="raise")\n\n @pytest.mark.parametrize(\n "timestamp",\n [\n "2018-01-01 0:0:0.124999360",\n "2018-01-01 0:0:0.125000367",\n "2018-01-01 0:0:0.125500",\n "2018-01-01 0:0:0.126500",\n "2018-01-01 12:00:00",\n "2019-01-01 12:00:00",\n ],\n )\n @pytest.mark.parametrize(\n "freq",\n [\n "2ns",\n "3ns",\n "4ns",\n "5ns",\n "6ns",\n "7ns",\n "250ns",\n "500ns",\n "750ns",\n "1us",\n "19us",\n "250us",\n "500us",\n "750us",\n "1s",\n "2s",\n "3s",\n "1D",\n ],\n )\n def test_round_int64(self, timestamp, freq):\n # check that all rounding modes are accurate to int64 precision\n # see GH#22591\n dt = Timestamp(timestamp).as_unit("ns")\n unit = to_offset(freq).nanos\n\n # test floor\n result = dt.floor(freq)\n assert result._value % unit == 0, f"floor not a {freq} multiple"\n assert 0 <= dt._value - result._value < unit, "floor error"\n\n # test ceil\n result = dt.ceil(freq)\n assert result._value % unit == 0, f"ceil not a {freq} multiple"\n assert 0 <= result._value - dt._value < unit, "ceil error"\n\n # test round\n result = dt.round(freq)\n assert result._value % unit == 0, f"round not a {freq} multiple"\n assert abs(result._value - dt._value) <= unit // 2, "round error"\n if unit % 2 == 0 and abs(result._value - dt._value) == unit // 2:\n # round half to even\n assert result._value // unit % 2 == 0, "round half to even error"\n\n def test_round_implementation_bounds(self):\n # See also: analogous test for Timedelta\n result = Timestamp.min.ceil("s")\n expected = Timestamp(1677, 9, 21, 0, 12, 44)\n assert result == expected\n\n result = Timestamp.max.floor("s")\n expected = Timestamp.max - Timedelta(854775807)\n assert result == expected\n\n msg = "Cannot round 1677-09-21 00:12:43.145224193 to freq=<Second>"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.min.floor("s")\n\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.min.round("s")\n\n msg = "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Second>"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.max.ceil("s")\n\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.max.round("s")\n\n @given(val=st.integers(iNaT + 1, lib.i8max))\n @pytest.mark.parametrize(\n "method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]\n )\n def test_round_sanity(self, val, method):\n cls = Timestamp\n err_cls = OutOfBoundsDatetime\n\n val = np.int64(val)\n ts = cls(val)\n\n def checker(ts, nanos, unit):\n # First check that we do raise in cases where we should\n if nanos == 1:\n pass\n else:\n div, mod = divmod(ts._value, nanos)\n diff = int(nanos - mod)\n lb = ts._value - mod\n assert lb <= ts._value # i.e. no overflows with python ints\n ub = ts._value + diff\n assert ub > ts._value # i.e. no overflows with python ints\n\n msg = "without overflow"\n if mod == 0:\n # We should never be raising in this\n pass\n elif method is cls.ceil:\n if ub > cls.max._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif method is cls.floor:\n if lb < cls.min._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif mod >= diff:\n if ub > cls.max._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n elif lb < cls.min._value:\n with pytest.raises(err_cls, match=msg):\n method(ts, unit)\n return\n\n res = method(ts, unit)\n\n td = res - ts\n diff = abs(td._value)\n assert diff < nanos\n assert res._value % nanos == 0\n\n if method is cls.round:\n assert diff <= nanos / 2\n elif method is cls.floor:\n assert res <= ts\n elif method is cls.ceil:\n assert res >= ts\n\n nanos = 1\n checker(ts, nanos, "ns")\n\n nanos = 1000\n checker(ts, nanos, "us")\n\n nanos = 1_000_000\n checker(ts, nanos, "ms")\n\n nanos = 1_000_000_000\n checker(ts, nanos, "s")\n\n nanos = 60 * 1_000_000_000\n checker(ts, nanos, "min")\n\n nanos = 60 * 60 * 1_000_000_000\n checker(ts, nanos, "h")\n\n nanos = 24 * 60 * 60 * 1_000_000_000\n checker(ts, nanos, "D")\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_round.py
test_round.py
Python
13,027
0.95
0.073107
0.048338
react-lib
832
2025-04-24T19:50:07.356496
GPL-3.0
true
709007210ec4e80eed3e64d64847475a
# NB: This is for the Timestamp.timestamp *method* specifically, not\n# the Timestamp class in general.\n\nfrom pytz import utc\n\nfrom pandas._libs.tslibs import Timestamp\nimport pandas.util._test_decorators as td\n\nimport pandas._testing as tm\n\n\nclass TestTimestampMethod:\n @td.skip_if_windows\n def test_timestamp(self, fixed_now_ts):\n # GH#17329\n # tz-naive --> treat it as if it were UTC for purposes of timestamp()\n ts = fixed_now_ts\n uts = ts.replace(tzinfo=utc)\n assert ts.timestamp() == uts.timestamp()\n\n tsc = Timestamp("2014-10-11 11:00:01.12345678", tz="US/Central")\n utsc = tsc.tz_convert("UTC")\n\n # utsc is a different representation of the same time\n assert tsc.timestamp() == utsc.timestamp()\n\n # datetime.timestamp() converts in the local timezone\n with tm.set_timezone("UTC"):\n # should agree with datetime.timestamp method\n dt = ts.to_pydatetime()\n assert dt.timestamp() == ts.timestamp()\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_timestamp_method.py
test_timestamp_method.py
Python
1,017
0.95
0.193548
0.304348
react-lib
326
2024-04-17T13:28:41.334473
Apache-2.0
true
ae8b178f36e31ac11aa773fabf812f36
from pandas import Timestamp\n\n\nclass TestTimestampToJulianDate:\n def test_compare_1700(self):\n ts = Timestamp("1700-06-23")\n res = ts.to_julian_date()\n assert res == 2_342_145.5\n\n def test_compare_2000(self):\n ts = Timestamp("2000-04-12")\n res = ts.to_julian_date()\n assert res == 2_451_646.5\n\n def test_compare_2100(self):\n ts = Timestamp("2100-08-12")\n res = ts.to_julian_date()\n assert res == 2_488_292.5\n\n def test_compare_hour01(self):\n ts = Timestamp("2000-08-12T01:00:00")\n res = ts.to_julian_date()\n assert res == 2_451_768.5416666666666666\n\n def test_compare_hour13(self):\n ts = Timestamp("2000-08-12T13:00:00")\n res = ts.to_julian_date()\n assert res == 2_451_769.0416666666666666\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_to_julian_date.py
test_to_julian_date.py
Python
810
0.85
0.214286
0
vue-tools
693
2024-05-01T15:39:09.156343
GPL-3.0
true
dc397bf79db0b317fd5402fbe07f4ff9
from datetime import (\n datetime,\n timedelta,\n)\n\nimport pytz\n\nfrom pandas._libs.tslibs.timezones import dateutil_gettz as gettz\nimport pandas.util._test_decorators as td\n\nfrom pandas import Timestamp\nimport pandas._testing as tm\n\n\nclass TestTimestampToPyDatetime:\n def test_to_pydatetime_fold(self):\n # GH#45087\n tzstr = "dateutil/usr/share/zoneinfo/America/Chicago"\n ts = Timestamp(year=2013, month=11, day=3, hour=1, minute=0, fold=1, tz=tzstr)\n dt = ts.to_pydatetime()\n assert dt.fold == 1\n\n def test_to_pydatetime_nonzero_nano(self):\n ts = Timestamp("2011-01-01 9:00:00.123456789")\n\n # Warn the user of data loss (nanoseconds).\n with tm.assert_produces_warning(UserWarning):\n expected = datetime(2011, 1, 1, 9, 0, 0, 123456)\n result = ts.to_pydatetime()\n assert result == expected\n\n def test_timestamp_to_datetime(self):\n stamp = Timestamp("20090415", tz="US/Eastern")\n dtval = stamp.to_pydatetime()\n assert stamp == dtval\n assert stamp.tzinfo == dtval.tzinfo\n\n def test_timestamp_to_pydatetime_dateutil(self):\n stamp = Timestamp("20090415", tz="dateutil/US/Eastern")\n dtval = stamp.to_pydatetime()\n assert stamp == dtval\n assert stamp.tzinfo == dtval.tzinfo\n\n def test_timestamp_to_pydatetime_explicit_pytz(self):\n stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern"))\n dtval = stamp.to_pydatetime()\n assert stamp == dtval\n assert stamp.tzinfo == dtval.tzinfo\n\n @td.skip_if_windows\n def test_timestamp_to_pydatetime_explicit_dateutil(self):\n stamp = Timestamp("20090415", tz=gettz("US/Eastern"))\n dtval = stamp.to_pydatetime()\n assert stamp == dtval\n assert stamp.tzinfo == dtval.tzinfo\n\n def test_to_pydatetime_bijective(self):\n # Ensure that converting to datetime and back only loses precision\n # by going from nanoseconds to microseconds.\n exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning\n with tm.assert_produces_warning(exp_warning):\n pydt_max = Timestamp.max.to_pydatetime()\n\n assert (\n Timestamp(pydt_max).as_unit("ns")._value / 1000\n == Timestamp.max._value / 1000\n )\n\n exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning\n with tm.assert_produces_warning(exp_warning):\n pydt_min = Timestamp.min.to_pydatetime()\n\n # The next assertion can be enabled once GH#39221 is merged\n # assert pydt_min < Timestamp.min # this is bc nanos are dropped\n tdus = timedelta(microseconds=1)\n assert pydt_min + tdus > Timestamp.min\n\n assert (\n Timestamp(pydt_min + tdus).as_unit("ns")._value / 1000\n == Timestamp.min._value / 1000\n )\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_to_pydatetime.py
test_to_pydatetime.py
Python
2,871
0.95
0.123457
0.092308
react-lib
867
2024-03-21T21:33:43.205636
BSD-3-Clause
true
2c691ed4d72cbea2937ea79179ee4955
import dateutil\nimport pytest\n\nfrom pandas._libs.tslibs import timezones\nimport pandas.util._test_decorators as td\n\nfrom pandas import Timestamp\n\n\nclass TestTimestampTZConvert:\n @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])\n def test_astimezone(self, tzstr):\n # astimezone is an alias for tz_convert, so keep it with\n # the tz_convert tests\n utcdate = Timestamp("3/11/2012 22:00", tz="UTC")\n expected = utcdate.tz_convert(tzstr)\n result = utcdate.astimezone(tzstr)\n assert expected == result\n assert isinstance(result, Timestamp)\n\n @pytest.mark.parametrize(\n "stamp",\n [\n "2014-02-01 09:00",\n "2014-07-08 09:00",\n "2014-11-01 17:00",\n "2014-11-05 00:00",\n ],\n )\n def test_tz_convert_roundtrip(self, stamp, tz_aware_fixture):\n tz = tz_aware_fixture\n\n ts = Timestamp(stamp, tz="UTC")\n converted = ts.tz_convert(tz)\n\n reset = converted.tz_convert(None)\n assert reset == Timestamp(stamp)\n assert reset.tzinfo is None\n assert reset == converted.tz_convert("UTC").tz_localize(None)\n\n @td.skip_if_windows\n def test_tz_convert_utc_with_system_utc(self):\n # from system utc to real utc\n ts = Timestamp("2001-01-05 11:56", tz=timezones.maybe_get_tz("dateutil/UTC"))\n # check that the time hasn't changed.\n assert ts == ts.tz_convert(dateutil.tz.tzutc())\n\n # from system utc to real utc\n ts = Timestamp("2001-01-05 11:56", tz=timezones.maybe_get_tz("dateutil/UTC"))\n # check that the time hasn't changed.\n assert ts == ts.tz_convert(dateutil.tz.tzutc())\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_tz_convert.py
test_tz_convert.py
Python
1,710
0.95
0.098039
0.142857
vue-tools
40
2024-02-02T12:36:12.074872
GPL-3.0
true
4b59c98a9518e0a6a308e53374e7bfbe
from datetime import timedelta\nimport re\n\nfrom dateutil.tz import gettz\nimport pytest\nimport pytz\nfrom pytz.exceptions import (\n AmbiguousTimeError,\n NonExistentTimeError,\n)\n\nfrom pandas._libs.tslibs.dtypes import NpyDatetimeUnit\nfrom pandas.errors import OutOfBoundsDatetime\n\nfrom pandas import (\n NaT,\n Timestamp,\n)\n\ntry:\n from zoneinfo import ZoneInfo\nexcept ImportError:\n # Cannot assign to a type\n ZoneInfo = None # type: ignore[misc, assignment]\n\n\nclass TestTimestampTZLocalize:\n @pytest.mark.skip_ubsan\n def test_tz_localize_pushes_out_of_bounds(self):\n # GH#12677\n # tz_localize that pushes away from the boundary is OK\n msg = (\n f"Converting {Timestamp.min.strftime('%Y-%m-%d %H:%M:%S')} "\n f"underflows past {Timestamp.min}"\n )\n pac = Timestamp.min.tz_localize("US/Pacific")\n assert pac._value > Timestamp.min._value\n pac.tz_convert("Asia/Tokyo") # tz_convert doesn't change value\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.min.tz_localize("Asia/Tokyo")\n\n # tz_localize that pushes away from the boundary is OK\n msg = (\n f"Converting {Timestamp.max.strftime('%Y-%m-%d %H:%M:%S')} "\n f"overflows past {Timestamp.max}"\n )\n tokyo = Timestamp.max.tz_localize("Asia/Tokyo")\n assert tokyo._value < Timestamp.max._value\n tokyo.tz_convert("US/Pacific") # tz_convert doesn't change value\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp.max.tz_localize("US/Pacific")\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_tz_localize_ambiguous_bool(self, unit):\n # make sure that we are correctly accepting bool values as ambiguous\n # GH#14402\n ts = Timestamp("2015-11-01 01:00:03").as_unit(unit)\n expected0 = Timestamp("2015-11-01 01:00:03-0500", tz="US/Central")\n expected1 = Timestamp("2015-11-01 01:00:03-0600", tz="US/Central")\n\n msg = "Cannot infer dst time from 2015-11-01 01:00:03"\n with pytest.raises(pytz.AmbiguousTimeError, match=msg):\n ts.tz_localize("US/Central")\n\n with pytest.raises(pytz.AmbiguousTimeError, match=msg):\n ts.tz_localize("dateutil/US/Central")\n\n if ZoneInfo is not None:\n try:\n tz = ZoneInfo("US/Central")\n except KeyError:\n # no tzdata\n pass\n else:\n with pytest.raises(pytz.AmbiguousTimeError, match=msg):\n ts.tz_localize(tz)\n\n result = ts.tz_localize("US/Central", ambiguous=True)\n assert result == expected0\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n result = ts.tz_localize("US/Central", ambiguous=False)\n assert result == expected1\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n def test_tz_localize_ambiguous(self):\n ts = Timestamp("2014-11-02 01:00")\n ts_dst = ts.tz_localize("US/Eastern", ambiguous=True)\n ts_no_dst = ts.tz_localize("US/Eastern", ambiguous=False)\n\n assert ts_no_dst._value - ts_dst._value == 3600\n msg = re.escape(\n "'ambiguous' parameter must be one of: "\n "True, False, 'NaT', 'raise' (default)"\n )\n with pytest.raises(ValueError, match=msg):\n ts.tz_localize("US/Eastern", ambiguous="infer")\n\n # GH#8025\n msg = "Cannot localize tz-aware Timestamp, use tz_convert for conversions"\n with pytest.raises(TypeError, match=msg):\n Timestamp("2011-01-01", tz="US/Eastern").tz_localize("Asia/Tokyo")\n\n msg = "Cannot convert tz-naive Timestamp, use tz_localize to localize"\n with pytest.raises(TypeError, match=msg):\n Timestamp("2011-01-01").tz_convert("Asia/Tokyo")\n\n @pytest.mark.parametrize(\n "stamp, tz",\n [\n ("2015-03-08 02:00", "US/Eastern"),\n ("2015-03-08 02:30", "US/Pacific"),\n ("2015-03-29 02:00", "Europe/Paris"),\n ("2015-03-29 02:30", "Europe/Belgrade"),\n ],\n )\n def test_tz_localize_nonexistent(self, stamp, tz):\n # GH#13057\n ts = Timestamp(stamp)\n with pytest.raises(NonExistentTimeError, match=stamp):\n ts.tz_localize(tz)\n # GH 22644\n with pytest.raises(NonExistentTimeError, match=stamp):\n ts.tz_localize(tz, nonexistent="raise")\n assert ts.tz_localize(tz, nonexistent="NaT") is NaT\n\n @pytest.mark.parametrize(\n "stamp, tz, forward_expected, backward_expected",\n [\n (\n "2015-03-29 02:00:00",\n "Europe/Warsaw",\n "2015-03-29 03:00:00",\n "2015-03-29 01:59:59",\n ), # utc+1 -> utc+2\n (\n "2023-03-12 02:00:00",\n "America/Los_Angeles",\n "2023-03-12 03:00:00",\n "2023-03-12 01:59:59",\n ), # utc-8 -> utc-7\n (\n "2023-03-26 01:00:00",\n "Europe/London",\n "2023-03-26 02:00:00",\n "2023-03-26 00:59:59",\n ), # utc+0 -> utc+1\n (\n "2023-03-26 00:00:00",\n "Atlantic/Azores",\n "2023-03-26 01:00:00",\n "2023-03-25 23:59:59",\n ), # utc-1 -> utc+0\n ],\n )\n def test_tz_localize_nonexistent_shift(\n self, stamp, tz, forward_expected, backward_expected\n ):\n ts = Timestamp(stamp)\n forward_ts = ts.tz_localize(tz, nonexistent="shift_forward")\n assert forward_ts == Timestamp(forward_expected, tz=tz)\n backward_ts = ts.tz_localize(tz, nonexistent="shift_backward")\n assert backward_ts == Timestamp(backward_expected, tz=tz)\n\n def test_tz_localize_ambiguous_raise(self):\n # GH#13057\n ts = Timestamp("2015-11-1 01:00")\n msg = "Cannot infer dst time from 2015-11-01 01:00:00,"\n with pytest.raises(AmbiguousTimeError, match=msg):\n ts.tz_localize("US/Pacific", ambiguous="raise")\n\n def test_tz_localize_nonexistent_invalid_arg(self, warsaw):\n # GH 22644\n tz = warsaw\n ts = Timestamp("2015-03-29 02:00:00")\n msg = (\n "The nonexistent argument must be one of 'raise', 'NaT', "\n "'shift_forward', 'shift_backward' or a timedelta object"\n )\n with pytest.raises(ValueError, match=msg):\n ts.tz_localize(tz, nonexistent="foo")\n\n @pytest.mark.parametrize(\n "stamp",\n [\n "2014-02-01 09:00",\n "2014-07-08 09:00",\n "2014-11-01 17:00",\n "2014-11-05 00:00",\n ],\n )\n def test_tz_localize_roundtrip(self, stamp, tz_aware_fixture):\n tz = tz_aware_fixture\n ts = Timestamp(stamp)\n localized = ts.tz_localize(tz)\n assert localized == Timestamp(stamp, tz=tz)\n\n msg = "Cannot localize tz-aware Timestamp"\n with pytest.raises(TypeError, match=msg):\n localized.tz_localize(tz)\n\n reset = localized.tz_localize(None)\n assert reset == ts\n assert reset.tzinfo is None\n\n def test_tz_localize_ambiguous_compat(self):\n # validate that pytz and dateutil are compat for dst\n # when the transition happens\n naive = Timestamp("2013-10-27 01:00:00")\n\n pytz_zone = "Europe/London"\n dateutil_zone = "dateutil/Europe/London"\n result_pytz = naive.tz_localize(pytz_zone, ambiguous=False)\n result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=False)\n assert result_pytz._value == result_dateutil._value\n assert result_pytz._value == 1382835600\n\n # fixed ambiguous behavior\n # see gh-14621, GH#45087\n assert result_pytz.to_pydatetime().tzname() == "GMT"\n assert result_dateutil.to_pydatetime().tzname() == "GMT"\n assert str(result_pytz) == str(result_dateutil)\n\n # 1 hour difference\n result_pytz = naive.tz_localize(pytz_zone, ambiguous=True)\n result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=True)\n assert result_pytz._value == result_dateutil._value\n assert result_pytz._value == 1382832000\n\n # see gh-14621\n assert str(result_pytz) == str(result_dateutil)\n assert (\n result_pytz.to_pydatetime().tzname()\n == result_dateutil.to_pydatetime().tzname()\n )\n\n @pytest.mark.parametrize(\n "tz",\n [\n pytz.timezone("US/Eastern"),\n gettz("US/Eastern"),\n "US/Eastern",\n "dateutil/US/Eastern",\n ],\n )\n def test_timestamp_tz_localize(self, tz):\n stamp = Timestamp("3/11/2012 04:00")\n\n result = stamp.tz_localize(tz)\n expected = Timestamp("3/11/2012 04:00", tz=tz)\n assert result.hour == expected.hour\n assert result == expected\n\n @pytest.mark.parametrize(\n "start_ts, tz, end_ts, shift",\n [\n ["2015-03-29 02:20:00", "Europe/Warsaw", "2015-03-29 03:00:00", "forward"],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 01:59:59.999999999",\n "backward",\n ],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 03:20:00",\n timedelta(hours=1),\n ],\n [\n "2015-03-29 02:20:00",\n "Europe/Warsaw",\n "2015-03-29 01:20:00",\n timedelta(hours=-1),\n ],\n ["2018-03-11 02:33:00", "US/Pacific", "2018-03-11 03:00:00", "forward"],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 01:59:59.999999999",\n "backward",\n ],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 03:33:00",\n timedelta(hours=1),\n ],\n [\n "2018-03-11 02:33:00",\n "US/Pacific",\n "2018-03-11 01:33:00",\n timedelta(hours=-1),\n ],\n ],\n )\n @pytest.mark.parametrize("tz_type", ["", "dateutil/"])\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_timestamp_tz_localize_nonexistent_shift(\n self, start_ts, tz, end_ts, shift, tz_type, unit\n ):\n # GH 8917, 24466\n tz = tz_type + tz\n if isinstance(shift, str):\n shift = "shift_" + shift\n ts = Timestamp(start_ts).as_unit(unit)\n result = ts.tz_localize(tz, nonexistent=shift)\n expected = Timestamp(end_ts).tz_localize(tz)\n\n if unit == "us":\n assert result == expected.replace(nanosecond=0)\n elif unit == "ms":\n micros = expected.microsecond - expected.microsecond % 1000\n assert result == expected.replace(microsecond=micros, nanosecond=0)\n elif unit == "s":\n assert result == expected.replace(microsecond=0, nanosecond=0)\n else:\n assert result == expected\n assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value\n\n @pytest.mark.parametrize("offset", [-1, 1])\n def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, warsaw):\n # GH 8917, 24466\n tz = warsaw\n ts = Timestamp("2015-03-29 02:20:00")\n msg = "The provided timedelta will relocalize on a nonexistent time"\n with pytest.raises(ValueError, match=msg):\n ts.tz_localize(tz, nonexistent=timedelta(seconds=offset))\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit):\n # GH 8917\n tz = warsaw\n ts = Timestamp("2015-03-29 02:20:00").as_unit(unit)\n result = ts.tz_localize(tz, nonexistent="NaT")\n assert result is NaT\n\n @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])\n def test_timestamp_tz_localize_nonexistent_raise(self, warsaw, unit):\n # GH 8917\n tz = warsaw\n ts = Timestamp("2015-03-29 02:20:00").as_unit(unit)\n msg = "2015-03-29 02:20:00"\n with pytest.raises(pytz.NonExistentTimeError, match=msg):\n ts.tz_localize(tz, nonexistent="raise")\n msg = (\n "The nonexistent argument must be one of 'raise', 'NaT', "\n "'shift_forward', 'shift_backward' or a timedelta object"\n )\n with pytest.raises(ValueError, match=msg):\n ts.tz_localize(tz, nonexistent="foo")\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\test_tz_localize.py
test_tz_localize.py
Python
12,774
0.95
0.062678
0.069841
vue-tools
798
2025-01-20T08:36:08.761360
MIT
true
de4e6397b48db77db87574b1c8ccd077
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_as_unit.cpython-313.pyc
test_as_unit.cpython-313.pyc
Other
5,473
0.8
0
0
vue-tools
760
2023-11-07T21:50:06.524344
MIT
true
88e436f8f85399bd6faf6e227f2a2434
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_normalize.cpython-313.pyc
test_normalize.cpython-313.pyc
Other
1,835
0.8
0
0.117647
react-lib
820
2023-11-12T01:13:23.632627
MIT
true
e897c5d4a11d35c5454faecab3cacd7e
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_replace.cpython-313.pyc
test_replace.cpython-313.pyc
Other
10,849
0.95
0.018182
0.046296
vue-tools
346
2025-04-13T12:18:02.923821
Apache-2.0
true
3a41f1f6e3a5aa3802111671aaa82f9a
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_round.cpython-313.pyc
test_round.cpython-313.pyc
Other
17,412
0.8
0
0
python-kit
257
2024-05-02T03:53:03.880310
Apache-2.0
true
da70cb02ed4c9dc4f8263d6da65325da
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_timestamp_method.cpython-313.pyc
test_timestamp_method.cpython-313.pyc
Other
1,700
0.8
0
0.230769
python-kit
346
2024-10-25T18:03:03.143105
BSD-3-Clause
true
dbb89172f005ca6785b89048300e31cd
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_to_julian_date.cpython-313.pyc
test_to_julian_date.cpython-313.pyc
Other
1,854
0.7
0
0
react-lib
355
2023-09-19T05:34:01.682876
MIT
true
3d450b5619ea32ba7939c14c1344da9f
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_to_pydatetime.cpython-313.pyc
test_to_pydatetime.cpython-313.pyc
Other
5,146
0.8
0
0
node-utils
729
2024-07-02T01:27:18.703974
BSD-3-Clause
true
799038124535786d7e532fe73ad95504
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_tz_convert.cpython-313.pyc
test_tz_convert.cpython-313.pyc
Other
2,899
0.8
0
0
awesome-app
205
2025-06-03T08:18:26.979645
GPL-3.0
true
48698a795fa308f5532f98f233c2bb62
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\test_tz_localize.cpython-313.pyc
test_tz_localize.cpython-313.pyc
Other
16,717
0.8
0.004405
0.004484
vue-tools
823
2025-07-06T12:53:37.961580
GPL-3.0
true
ec60c87f942027c9bdd250fe124a78f8
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\methods\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
212
0.7
0
0
react-lib
270
2025-04-09T16:54:28.357555
GPL-3.0
true
ec0d3f513f3a1537116a0e69f289aa40
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_arithmetic.cpython-313.pyc
test_arithmetic.cpython-313.pyc
Other
17,012
0.8
0.004167
0.016807
node-utils
780
2023-07-20T08:32:00.340602
BSD-3-Clause
true
c2e8fb98d1cbc0f8e6755530a6b3f330
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_comparisons.cpython-313.pyc
test_comparisons.cpython-313.pyc
Other
15,591
0.8
0
0
python-kit
291
2024-09-20T01:17:46.052295
MIT
true
191235b7188b1130468edf38d8a5dcfb
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_constructors.cpython-313.pyc
test_constructors.cpython-313.pyc
Other
52,945
0.95
0.005155
0.012153
python-kit
345
2025-02-25T07:04:39.054932
MIT
true
0c84a2fb4add5f35cda151d8025b2b01
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_formats.cpython-313.pyc
test_formats.cpython-313.pyc
Other
8,814
0.8
0
0
python-kit
97
2023-08-06T15:17:55.010325
BSD-3-Clause
true
fcb5dfb8cdd176ca074f994533a815c9
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_timestamp.cpython-313.pyc
test_timestamp.cpython-313.pyc
Other
50,281
0.8
0
0.006696
python-kit
901
2025-02-22T06:33:07.324726
Apache-2.0
true
28288e121b7b553c0bb955489025cda5
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\test_timezones.cpython-313.pyc
test_timezones.cpython-313.pyc
Other
1,318
0.8
0.0625
0.133333
node-utils
303
2024-05-15T10:22:47.901193
MIT
true
950323d2f39eaad34cdcdb162ff01314
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\timestamp\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
204
0.7
0
0
react-lib
582
2023-09-04T16:01:31.374008
Apache-2.0
true
27b79ac6f31c2f102759d043597f2482
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\__pycache__\test_nat.cpython-313.pyc
test_nat.cpython-313.pyc
Other
27,033
0.95
0.01476
0.003774
python-kit
288
2025-03-07T21:52:51.478714
BSD-3-Clause
true
f061340bcca9629b6e1266a06c7ce762
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\__pycache__\test_na_scalar.cpython-313.pyc
test_na_scalar.cpython-313.pyc
Other
15,198
0.95
0
0
vue-tools
610
2025-06-01T17:16:20.504081
MIT
true
026d9bbb07dd1ff00d2d06751caa1d4a
\n\n
.venv\Lib\site-packages\pandas\tests\scalar\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
194
0.7
0
0
node-utils
296
2023-09-25T17:44:54.787235
GPL-3.0
true
98acdc674a6641b43d7827a419400a95
import inspect\nimport pydoc\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n DataFrame,\n Index,\n Series,\n date_range,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\n\n\nclass TestSeriesMisc:\n def test_tab_completion(self):\n # GH 9910\n s = Series(list("abcd"))\n # Series of str values should have .str but not .dt/.cat in __dir__\n assert "str" in dir(s)\n assert "dt" not in dir(s)\n assert "cat" not in dir(s)\n\n def test_tab_completion_dt(self):\n # similarly for .dt\n s = Series(date_range("1/1/2015", periods=5))\n assert "dt" in dir(s)\n assert "str" not in dir(s)\n assert "cat" not in dir(s)\n\n def test_tab_completion_cat(self):\n # Similarly for .cat, but with the twist that str and dt should be\n # there if the categories are of that type first cat and str.\n s = Series(list("abbcd"), dtype="category")\n assert "cat" in dir(s)\n assert "str" in dir(s) # as it is a string categorical\n assert "dt" not in dir(s)\n\n def test_tab_completion_cat_str(self):\n # similar to cat and str\n s = Series(date_range("1/1/2015", periods=5)).astype("category")\n assert "cat" in dir(s)\n assert "str" not in dir(s)\n assert "dt" in dir(s) # as it is a datetime categorical\n\n def test_tab_completion_with_categorical(self):\n # test the tab completion display\n ok_for_cat = [\n "categories",\n "codes",\n "ordered",\n "set_categories",\n "add_categories",\n "remove_categories",\n "rename_categories",\n "reorder_categories",\n "remove_unused_categories",\n "as_ordered",\n "as_unordered",\n ]\n\n s = Series(list("aabbcde")).astype("category")\n results = sorted({r for r in s.cat.__dir__() if not r.startswith("_")})\n tm.assert_almost_equal(results, sorted(set(ok_for_cat)))\n\n @pytest.mark.parametrize(\n "index",\n [\n Index(list("ab") * 5, dtype="category"),\n Index([str(i) for i in range(10)]),\n Index(["foo", "bar", "baz"] * 2),\n date_range("2020-01-01", periods=10),\n period_range("2020-01-01", periods=10, freq="D"),\n timedelta_range("1 day", periods=10),\n Index(np.arange(10), dtype=np.uint64),\n Index(np.arange(10), dtype=np.int64),\n Index(np.arange(10), dtype=np.float64),\n Index([True, False]),\n Index([f"a{i}" for i in range(101)]),\n pd.MultiIndex.from_tuples(zip("ABCD", "EFGH")),\n pd.MultiIndex.from_tuples(zip([0, 1, 2, 3], "EFGH")),\n ],\n )\n def test_index_tab_completion(self, index):\n # dir contains string-like values of the Index.\n s = Series(index=index, dtype=object)\n dir_s = dir(s)\n for i, x in enumerate(s.index.unique(level=0)):\n if i < 100:\n assert not isinstance(x, str) or not x.isidentifier() or x in dir_s\n else:\n assert x not in dir_s\n\n @pytest.mark.parametrize("ser", [Series(dtype=object), Series([1])])\n def test_not_hashable(self, ser):\n msg = "unhashable type: 'Series'"\n with pytest.raises(TypeError, match=msg):\n hash(ser)\n\n def test_contains(self, datetime_series):\n tm.assert_contains_all(datetime_series.index, datetime_series)\n\n def test_axis_alias(self):\n s = Series([1, 2, np.nan])\n tm.assert_series_equal(s.dropna(axis="rows"), s.dropna(axis="index"))\n assert s.dropna().sum("rows") == 3\n assert s._get_axis_number("rows") == 0\n assert s._get_axis_name("rows") == "index"\n\n def test_class_axis(self):\n # https://github.com/pandas-dev/pandas/issues/18147\n # no exception and no empty docstring\n assert pydoc.getdoc(Series.index)\n\n def test_ndarray_compat(self):\n # test numpy compat with Series as sub-class of NDFrame\n tsdf = DataFrame(\n np.random.default_rng(2).standard_normal((1000, 3)),\n columns=["A", "B", "C"],\n index=date_range("1/1/2000", periods=1000),\n )\n\n def f(x):\n return x[x.idxmax()]\n\n result = tsdf.apply(f)\n expected = tsdf.max()\n tm.assert_series_equal(result, expected)\n\n def test_ndarray_compat_like_func(self):\n # using an ndarray like function\n s = Series(np.random.default_rng(2).standard_normal(10))\n result = Series(np.ones_like(s))\n expected = Series(1, index=range(10), dtype="float64")\n tm.assert_series_equal(result, expected)\n\n def test_ndarray_compat_ravel(self):\n # ravel\n s = Series(np.random.default_rng(2).standard_normal(10))\n with tm.assert_produces_warning(FutureWarning, match="ravel is deprecated"):\n result = s.ravel(order="F")\n tm.assert_almost_equal(result, s.values.ravel(order="F"))\n\n def test_empty_method(self):\n s_empty = Series(dtype=object)\n assert s_empty.empty\n\n @pytest.mark.parametrize("dtype", ["int64", object])\n def test_empty_method_full_series(self, dtype):\n full_series = Series(index=[1], dtype=dtype)\n assert not full_series.empty\n\n @pytest.mark.parametrize("dtype", [None, "Int64"])\n def test_integer_series_size(self, dtype):\n # GH 25580\n s = Series(range(9), dtype=dtype)\n assert s.size == 9\n\n def test_attrs(self):\n s = Series([0, 1], name="abc")\n assert s.attrs == {}\n s.attrs["version"] = 1\n result = s + 1\n assert result.attrs == {"version": 1}\n\n def test_inspect_getmembers(self):\n # GH38782\n ser = Series(dtype=object)\n msg = "Series._data is deprecated"\n with tm.assert_produces_warning(\n DeprecationWarning, match=msg, check_stacklevel=False\n ):\n inspect.getmembers(ser)\n\n def test_unknown_attribute(self):\n # GH#9680\n tdi = timedelta_range(start=0, periods=10, freq="1s")\n ser = Series(np.random.default_rng(2).normal(size=10), index=tdi)\n assert "foo" not in ser.__dict__\n msg = "'Series' object has no attribute 'foo'"\n with pytest.raises(AttributeError, match=msg):\n ser.foo\n\n @pytest.mark.parametrize("op", ["year", "day", "second", "weekday"])\n def test_datetime_series_no_datelike_attrs(self, op, datetime_series):\n # GH#7206\n msg = f"'Series' object has no attribute '{op}'"\n with pytest.raises(AttributeError, match=msg):\n getattr(datetime_series, op)\n\n def test_series_datetimelike_attribute_access(self):\n # attribute access should still work!\n ser = Series({"year": 2000, "month": 1, "day": 10})\n assert ser.year == 2000\n assert ser.month == 1\n assert ser.day == 10\n\n def test_series_datetimelike_attribute_access_invalid(self):\n ser = Series({"year": 2000, "month": 1, "day": 10})\n msg = "'Series' object has no attribute 'weekday'"\n with pytest.raises(AttributeError, match=msg):\n ser.weekday\n\n @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning")\n @pytest.mark.parametrize(\n "kernel, has_numeric_only",\n [\n ("skew", True),\n ("var", True),\n ("all", False),\n ("prod", True),\n ("any", False),\n ("idxmin", False),\n ("quantile", False),\n ("idxmax", False),\n ("min", True),\n ("sem", True),\n ("mean", True),\n ("nunique", False),\n ("max", True),\n ("sum", True),\n ("count", False),\n ("median", True),\n ("std", True),\n ("backfill", False),\n ("rank", True),\n ("pct_change", False),\n ("cummax", False),\n ("shift", False),\n ("diff", False),\n ("cumsum", False),\n ("cummin", False),\n ("cumprod", False),\n ("fillna", False),\n ("ffill", False),\n ("pad", False),\n ("bfill", False),\n ("sample", False),\n ("tail", False),\n ("take", False),\n ("head", False),\n ("cov", False),\n ("corr", False),\n ],\n )\n @pytest.mark.parametrize("dtype", [bool, int, float, object])\n def test_numeric_only(self, kernel, has_numeric_only, dtype):\n # GH#47500\n ser = Series([0, 1, 1], dtype=dtype)\n if kernel == "corrwith":\n args = (ser,)\n elif kernel == "corr":\n args = (ser,)\n elif kernel == "cov":\n args = (ser,)\n elif kernel == "nth":\n args = (0,)\n elif kernel == "fillna":\n args = (True,)\n elif kernel == "fillna":\n args = ("ffill",)\n elif kernel == "take":\n args = ([0],)\n elif kernel == "quantile":\n args = (0.5,)\n else:\n args = ()\n method = getattr(ser, kernel)\n if not has_numeric_only:\n msg = (\n "(got an unexpected keyword argument 'numeric_only'"\n "|too many arguments passed in)"\n )\n with pytest.raises(TypeError, match=msg):\n method(*args, numeric_only=True)\n elif dtype is object:\n msg = f"Series.{kernel} does not allow numeric_only=True with non-numeric"\n with pytest.raises(TypeError, match=msg):\n method(*args, numeric_only=True)\n else:\n result = method(*args, numeric_only=True)\n expected = method(*args, numeric_only=False)\n if isinstance(expected, Series):\n # transformer\n tm.assert_series_equal(result, expected)\n else:\n # reducer\n assert result == expected\n\n\n@pytest.mark.parametrize("converter", [int, float, complex])\ndef test_float_int_deprecated(converter):\n # GH 51101\n with tm.assert_produces_warning(FutureWarning):\n assert converter(Series([1])) == converter(1)\n
.venv\Lib\site-packages\pandas\tests\series\test_api.py
test_api.py
Python
10,301
0.95
0.133779
0.08209
vue-tools
767
2023-12-06T15:52:26.824713
GPL-3.0
true
98b575398a8eac60e78d902aed075861