Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/interval/test_constructors.py +51 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/period/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/period/test_arithmetic.py +486 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/test_na_scalar.py +316 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/test_nat.py +709 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_constructors.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_formats.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_timedelta.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/test_as_unit.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/test_round.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/test_as_unit.py +80 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/test_round.py +187 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_arithmetic.py +1182 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_constructors.py +698 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_formats.py +109 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_timedelta.py +666 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timestamp.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_as_unit.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_normalize.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_replace.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_round.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_timestamp_method.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_to_julian_date.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_to_pydatetime.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_convert.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_localize.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_as_unit.py +86 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_normalize.py +22 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_replace.py +193 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_round.py +383 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_timestamp_method.py +31 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_to_julian_date.py +28 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_to_pydatetime.py +81 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_tz_convert.py +51 -0
- llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_tz_localize.py +351 -0
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/interval/test_constructors.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import (
|
4 |
+
Interval,
|
5 |
+
Period,
|
6 |
+
Timestamp,
|
7 |
+
)
|
8 |
+
|
9 |
+
|
10 |
+
class TestIntervalConstructors:
|
11 |
+
@pytest.mark.parametrize(
|
12 |
+
"left, right",
|
13 |
+
[
|
14 |
+
("a", "z"),
|
15 |
+
(("a", "b"), ("c", "d")),
|
16 |
+
(list("AB"), list("ab")),
|
17 |
+
(Interval(0, 1), Interval(1, 2)),
|
18 |
+
(Period("2018Q1", freq="Q"), Period("2018Q1", freq="Q")),
|
19 |
+
],
|
20 |
+
)
|
21 |
+
def test_construct_errors(self, left, right):
|
22 |
+
# GH#23013
|
23 |
+
msg = "Only numeric, Timestamp and Timedelta endpoints are allowed"
|
24 |
+
with pytest.raises(ValueError, match=msg):
|
25 |
+
Interval(left, right)
|
26 |
+
|
27 |
+
def test_constructor_errors(self):
|
28 |
+
msg = "invalid option for 'closed': foo"
|
29 |
+
with pytest.raises(ValueError, match=msg):
|
30 |
+
Interval(0, 1, closed="foo")
|
31 |
+
|
32 |
+
msg = "left side of interval must be <= right side"
|
33 |
+
with pytest.raises(ValueError, match=msg):
|
34 |
+
Interval(1, 0)
|
35 |
+
|
36 |
+
@pytest.mark.parametrize(
|
37 |
+
"tz_left, tz_right", [(None, "UTC"), ("UTC", None), ("UTC", "US/Eastern")]
|
38 |
+
)
|
39 |
+
def test_constructor_errors_tz(self, tz_left, tz_right):
|
40 |
+
# GH#18538
|
41 |
+
left = Timestamp("2017-01-01", tz=tz_left)
|
42 |
+
right = Timestamp("2017-01-02", tz=tz_right)
|
43 |
+
|
44 |
+
if tz_left is None or tz_right is None:
|
45 |
+
error = TypeError
|
46 |
+
msg = "Cannot compare tz-naive and tz-aware timestamps"
|
47 |
+
else:
|
48 |
+
error = ValueError
|
49 |
+
msg = "left and right must have the same time zone"
|
50 |
+
with pytest.raises(error, match=msg):
|
51 |
+
Interval(left, right)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/period/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/period/test_arithmetic.py
ADDED
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
import pytest
|
5 |
+
|
6 |
+
from pandas._libs.tslibs.period import IncompatibleFrequency
|
7 |
+
|
8 |
+
from pandas import (
|
9 |
+
NaT,
|
10 |
+
Period,
|
11 |
+
Timedelta,
|
12 |
+
Timestamp,
|
13 |
+
offsets,
|
14 |
+
)
|
15 |
+
|
16 |
+
|
17 |
+
class TestPeriodArithmetic:
|
18 |
+
def test_add_overflow_raises(self):
|
19 |
+
# GH#55503
|
20 |
+
per = Timestamp.max.to_period("ns")
|
21 |
+
|
22 |
+
msg = "|".join(
|
23 |
+
[
|
24 |
+
"Python int too large to convert to C long",
|
25 |
+
# windows, 32bit linux builds
|
26 |
+
"int too big to convert",
|
27 |
+
]
|
28 |
+
)
|
29 |
+
with pytest.raises(OverflowError, match=msg):
|
30 |
+
per + 1
|
31 |
+
|
32 |
+
msg = "value too large"
|
33 |
+
with pytest.raises(OverflowError, match=msg):
|
34 |
+
per + Timedelta(1)
|
35 |
+
with pytest.raises(OverflowError, match=msg):
|
36 |
+
per + offsets.Nano(1)
|
37 |
+
|
38 |
+
def test_period_add_integer(self):
|
39 |
+
per1 = Period(freq="D", year=2008, month=1, day=1)
|
40 |
+
per2 = Period(freq="D", year=2008, month=1, day=2)
|
41 |
+
assert per1 + 1 == per2
|
42 |
+
assert 1 + per1 == per2
|
43 |
+
|
44 |
+
def test_period_add_invalid(self):
|
45 |
+
# GH#4731
|
46 |
+
per1 = Period(freq="D", year=2008, month=1, day=1)
|
47 |
+
per2 = Period(freq="D", year=2008, month=1, day=2)
|
48 |
+
|
49 |
+
msg = "|".join(
|
50 |
+
[
|
51 |
+
r"unsupported operand type\(s\)",
|
52 |
+
"can only concatenate str",
|
53 |
+
"must be str, not Period",
|
54 |
+
]
|
55 |
+
)
|
56 |
+
with pytest.raises(TypeError, match=msg):
|
57 |
+
per1 + "str"
|
58 |
+
with pytest.raises(TypeError, match=msg):
|
59 |
+
"str" + per1
|
60 |
+
with pytest.raises(TypeError, match=msg):
|
61 |
+
per1 + per2
|
62 |
+
|
63 |
+
def test_period_sub_period_annual(self):
|
64 |
+
left, right = Period("2011", freq="Y"), Period("2007", freq="Y")
|
65 |
+
result = left - right
|
66 |
+
assert result == 4 * right.freq
|
67 |
+
|
68 |
+
msg = r"Input has different freq=M from Period\(freq=Y-DEC\)"
|
69 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
70 |
+
left - Period("2007-01", freq="M")
|
71 |
+
|
72 |
+
def test_period_sub_period(self):
|
73 |
+
per1 = Period("2011-01-01", freq="D")
|
74 |
+
per2 = Period("2011-01-15", freq="D")
|
75 |
+
|
76 |
+
off = per1.freq
|
77 |
+
assert per1 - per2 == -14 * off
|
78 |
+
assert per2 - per1 == 14 * off
|
79 |
+
|
80 |
+
msg = r"Input has different freq=M from Period\(freq=D\)"
|
81 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
82 |
+
per1 - Period("2011-02", freq="M")
|
83 |
+
|
84 |
+
@pytest.mark.parametrize("n", [1, 2, 3, 4])
|
85 |
+
def test_sub_n_gt_1_ticks(self, tick_classes, n):
|
86 |
+
# GH#23878
|
87 |
+
p1 = Period("19910905", freq=tick_classes(n))
|
88 |
+
p2 = Period("19920406", freq=tick_classes(n))
|
89 |
+
|
90 |
+
expected = Period(str(p2), freq=p2.freq.base) - Period(
|
91 |
+
str(p1), freq=p1.freq.base
|
92 |
+
)
|
93 |
+
|
94 |
+
assert (p2 - p1) == expected
|
95 |
+
|
96 |
+
@pytest.mark.parametrize("normalize", [True, False])
|
97 |
+
@pytest.mark.parametrize("n", [1, 2, 3, 4])
|
98 |
+
@pytest.mark.parametrize(
|
99 |
+
"offset, kwd_name",
|
100 |
+
[
|
101 |
+
(offsets.YearEnd, "month"),
|
102 |
+
(offsets.QuarterEnd, "startingMonth"),
|
103 |
+
(offsets.MonthEnd, None),
|
104 |
+
(offsets.Week, "weekday"),
|
105 |
+
],
|
106 |
+
)
|
107 |
+
def test_sub_n_gt_1_offsets(self, offset, kwd_name, n, normalize):
|
108 |
+
# GH#23878
|
109 |
+
kwds = {kwd_name: 3} if kwd_name is not None else {}
|
110 |
+
p1_d = "19910905"
|
111 |
+
p2_d = "19920406"
|
112 |
+
p1 = Period(p1_d, freq=offset(n, normalize, **kwds))
|
113 |
+
p2 = Period(p2_d, freq=offset(n, normalize, **kwds))
|
114 |
+
|
115 |
+
expected = Period(p2_d, freq=p2.freq.base) - Period(p1_d, freq=p1.freq.base)
|
116 |
+
|
117 |
+
assert (p2 - p1) == expected
|
118 |
+
|
119 |
+
def test_period_add_offset(self):
|
120 |
+
# freq is DateOffset
|
121 |
+
for freq in ["Y", "2Y", "3Y"]:
|
122 |
+
per = Period("2011", freq=freq)
|
123 |
+
exp = Period("2013", freq=freq)
|
124 |
+
assert per + offsets.YearEnd(2) == exp
|
125 |
+
assert offsets.YearEnd(2) + per == exp
|
126 |
+
|
127 |
+
for off in [
|
128 |
+
offsets.YearBegin(2),
|
129 |
+
offsets.MonthBegin(1),
|
130 |
+
offsets.Minute(),
|
131 |
+
np.timedelta64(365, "D"),
|
132 |
+
timedelta(365),
|
133 |
+
]:
|
134 |
+
msg = "Input has different freq|Input cannot be converted to Period"
|
135 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
136 |
+
per + off
|
137 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
138 |
+
off + per
|
139 |
+
|
140 |
+
for freq in ["M", "2M", "3M"]:
|
141 |
+
per = Period("2011-03", freq=freq)
|
142 |
+
exp = Period("2011-05", freq=freq)
|
143 |
+
assert per + offsets.MonthEnd(2) == exp
|
144 |
+
assert offsets.MonthEnd(2) + per == exp
|
145 |
+
|
146 |
+
exp = Period("2012-03", freq=freq)
|
147 |
+
assert per + offsets.MonthEnd(12) == exp
|
148 |
+
assert offsets.MonthEnd(12) + per == exp
|
149 |
+
|
150 |
+
msg = "|".join(
|
151 |
+
[
|
152 |
+
"Input has different freq",
|
153 |
+
"Input cannot be converted to Period",
|
154 |
+
]
|
155 |
+
)
|
156 |
+
|
157 |
+
for off in [
|
158 |
+
offsets.YearBegin(2),
|
159 |
+
offsets.MonthBegin(1),
|
160 |
+
offsets.Minute(),
|
161 |
+
np.timedelta64(365, "D"),
|
162 |
+
timedelta(365),
|
163 |
+
]:
|
164 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
165 |
+
per + off
|
166 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
167 |
+
off + per
|
168 |
+
|
169 |
+
# freq is Tick
|
170 |
+
for freq in ["D", "2D", "3D"]:
|
171 |
+
per = Period("2011-04-01", freq=freq)
|
172 |
+
|
173 |
+
exp = Period("2011-04-06", freq=freq)
|
174 |
+
assert per + offsets.Day(5) == exp
|
175 |
+
assert offsets.Day(5) + per == exp
|
176 |
+
|
177 |
+
exp = Period("2011-04-02", freq=freq)
|
178 |
+
assert per + offsets.Hour(24) == exp
|
179 |
+
assert offsets.Hour(24) + per == exp
|
180 |
+
|
181 |
+
exp = Period("2011-04-03", freq=freq)
|
182 |
+
assert per + np.timedelta64(2, "D") == exp
|
183 |
+
assert np.timedelta64(2, "D") + per == exp
|
184 |
+
|
185 |
+
exp = Period("2011-04-02", freq=freq)
|
186 |
+
assert per + np.timedelta64(3600 * 24, "s") == exp
|
187 |
+
assert np.timedelta64(3600 * 24, "s") + per == exp
|
188 |
+
|
189 |
+
exp = Period("2011-03-30", freq=freq)
|
190 |
+
assert per + timedelta(-2) == exp
|
191 |
+
assert timedelta(-2) + per == exp
|
192 |
+
|
193 |
+
exp = Period("2011-04-03", freq=freq)
|
194 |
+
assert per + timedelta(hours=48) == exp
|
195 |
+
assert timedelta(hours=48) + per == exp
|
196 |
+
|
197 |
+
msg = "|".join(
|
198 |
+
[
|
199 |
+
"Input has different freq",
|
200 |
+
"Input cannot be converted to Period",
|
201 |
+
]
|
202 |
+
)
|
203 |
+
|
204 |
+
for off in [
|
205 |
+
offsets.YearBegin(2),
|
206 |
+
offsets.MonthBegin(1),
|
207 |
+
offsets.Minute(),
|
208 |
+
np.timedelta64(4, "h"),
|
209 |
+
timedelta(hours=23),
|
210 |
+
]:
|
211 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
212 |
+
per + off
|
213 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
214 |
+
off + per
|
215 |
+
|
216 |
+
for freq in ["h", "2h", "3h"]:
|
217 |
+
per = Period("2011-04-01 09:00", freq=freq)
|
218 |
+
|
219 |
+
exp = Period("2011-04-03 09:00", freq=freq)
|
220 |
+
assert per + offsets.Day(2) == exp
|
221 |
+
assert offsets.Day(2) + per == exp
|
222 |
+
|
223 |
+
exp = Period("2011-04-01 12:00", freq=freq)
|
224 |
+
assert per + offsets.Hour(3) == exp
|
225 |
+
assert offsets.Hour(3) + per == exp
|
226 |
+
|
227 |
+
msg = "cannot use operands with types"
|
228 |
+
exp = Period("2011-04-01 12:00", freq=freq)
|
229 |
+
assert per + np.timedelta64(3, "h") == exp
|
230 |
+
assert np.timedelta64(3, "h") + per == exp
|
231 |
+
|
232 |
+
exp = Period("2011-04-01 10:00", freq=freq)
|
233 |
+
assert per + np.timedelta64(3600, "s") == exp
|
234 |
+
assert np.timedelta64(3600, "s") + per == exp
|
235 |
+
|
236 |
+
exp = Period("2011-04-01 11:00", freq=freq)
|
237 |
+
assert per + timedelta(minutes=120) == exp
|
238 |
+
assert timedelta(minutes=120) + per == exp
|
239 |
+
|
240 |
+
exp = Period("2011-04-05 12:00", freq=freq)
|
241 |
+
assert per + timedelta(days=4, minutes=180) == exp
|
242 |
+
assert timedelta(days=4, minutes=180) + per == exp
|
243 |
+
|
244 |
+
msg = "|".join(
|
245 |
+
[
|
246 |
+
"Input has different freq",
|
247 |
+
"Input cannot be converted to Period",
|
248 |
+
]
|
249 |
+
)
|
250 |
+
|
251 |
+
for off in [
|
252 |
+
offsets.YearBegin(2),
|
253 |
+
offsets.MonthBegin(1),
|
254 |
+
offsets.Minute(),
|
255 |
+
np.timedelta64(3200, "s"),
|
256 |
+
timedelta(hours=23, minutes=30),
|
257 |
+
]:
|
258 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
259 |
+
per + off
|
260 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
261 |
+
off + per
|
262 |
+
|
263 |
+
def test_period_sub_offset(self):
|
264 |
+
# freq is DateOffset
|
265 |
+
msg = "|".join(
|
266 |
+
[
|
267 |
+
"Input has different freq",
|
268 |
+
"Input cannot be converted to Period",
|
269 |
+
]
|
270 |
+
)
|
271 |
+
|
272 |
+
for freq in ["Y", "2Y", "3Y"]:
|
273 |
+
per = Period("2011", freq=freq)
|
274 |
+
assert per - offsets.YearEnd(2) == Period("2009", freq=freq)
|
275 |
+
|
276 |
+
for off in [
|
277 |
+
offsets.YearBegin(2),
|
278 |
+
offsets.MonthBegin(1),
|
279 |
+
offsets.Minute(),
|
280 |
+
np.timedelta64(365, "D"),
|
281 |
+
timedelta(365),
|
282 |
+
]:
|
283 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
284 |
+
per - off
|
285 |
+
|
286 |
+
for freq in ["M", "2M", "3M"]:
|
287 |
+
per = Period("2011-03", freq=freq)
|
288 |
+
assert per - offsets.MonthEnd(2) == Period("2011-01", freq=freq)
|
289 |
+
assert per - offsets.MonthEnd(12) == Period("2010-03", freq=freq)
|
290 |
+
|
291 |
+
for off in [
|
292 |
+
offsets.YearBegin(2),
|
293 |
+
offsets.MonthBegin(1),
|
294 |
+
offsets.Minute(),
|
295 |
+
np.timedelta64(365, "D"),
|
296 |
+
timedelta(365),
|
297 |
+
]:
|
298 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
299 |
+
per - off
|
300 |
+
|
301 |
+
# freq is Tick
|
302 |
+
for freq in ["D", "2D", "3D"]:
|
303 |
+
per = Period("2011-04-01", freq=freq)
|
304 |
+
assert per - offsets.Day(5) == Period("2011-03-27", freq=freq)
|
305 |
+
assert per - offsets.Hour(24) == Period("2011-03-31", freq=freq)
|
306 |
+
assert per - np.timedelta64(2, "D") == Period("2011-03-30", freq=freq)
|
307 |
+
assert per - np.timedelta64(3600 * 24, "s") == Period(
|
308 |
+
"2011-03-31", freq=freq
|
309 |
+
)
|
310 |
+
assert per - timedelta(-2) == Period("2011-04-03", freq=freq)
|
311 |
+
assert per - timedelta(hours=48) == Period("2011-03-30", freq=freq)
|
312 |
+
|
313 |
+
for off in [
|
314 |
+
offsets.YearBegin(2),
|
315 |
+
offsets.MonthBegin(1),
|
316 |
+
offsets.Minute(),
|
317 |
+
np.timedelta64(4, "h"),
|
318 |
+
timedelta(hours=23),
|
319 |
+
]:
|
320 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
321 |
+
per - off
|
322 |
+
|
323 |
+
for freq in ["h", "2h", "3h"]:
|
324 |
+
per = Period("2011-04-01 09:00", freq=freq)
|
325 |
+
assert per - offsets.Day(2) == Period("2011-03-30 09:00", freq=freq)
|
326 |
+
assert per - offsets.Hour(3) == Period("2011-04-01 06:00", freq=freq)
|
327 |
+
assert per - np.timedelta64(3, "h") == Period("2011-04-01 06:00", freq=freq)
|
328 |
+
assert per - np.timedelta64(3600, "s") == Period(
|
329 |
+
"2011-04-01 08:00", freq=freq
|
330 |
+
)
|
331 |
+
assert per - timedelta(minutes=120) == Period("2011-04-01 07:00", freq=freq)
|
332 |
+
assert per - timedelta(days=4, minutes=180) == Period(
|
333 |
+
"2011-03-28 06:00", freq=freq
|
334 |
+
)
|
335 |
+
|
336 |
+
for off in [
|
337 |
+
offsets.YearBegin(2),
|
338 |
+
offsets.MonthBegin(1),
|
339 |
+
offsets.Minute(),
|
340 |
+
np.timedelta64(3200, "s"),
|
341 |
+
timedelta(hours=23, minutes=30),
|
342 |
+
]:
|
343 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
344 |
+
per - off
|
345 |
+
|
346 |
+
@pytest.mark.parametrize("freq", ["M", "2M", "3M"])
|
347 |
+
def test_period_addsub_nat(self, freq):
|
348 |
+
# GH#13071
|
349 |
+
per = Period("2011-01", freq=freq)
|
350 |
+
|
351 |
+
# For subtraction, NaT is treated as another Period object
|
352 |
+
assert NaT - per is NaT
|
353 |
+
assert per - NaT is NaT
|
354 |
+
|
355 |
+
# For addition, NaT is treated as offset-like
|
356 |
+
assert NaT + per is NaT
|
357 |
+
assert per + NaT is NaT
|
358 |
+
|
359 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "m"])
|
360 |
+
def test_period_add_sub_td64_nat(self, unit):
|
361 |
+
# GH#47196
|
362 |
+
per = Period("2022-06-01", "D")
|
363 |
+
nat = np.timedelta64("NaT", unit)
|
364 |
+
|
365 |
+
assert per + nat is NaT
|
366 |
+
assert nat + per is NaT
|
367 |
+
assert per - nat is NaT
|
368 |
+
|
369 |
+
with pytest.raises(TypeError, match="unsupported operand"):
|
370 |
+
nat - per
|
371 |
+
|
372 |
+
def test_period_ops_offset(self):
|
373 |
+
per = Period("2011-04-01", freq="D")
|
374 |
+
result = per + offsets.Day()
|
375 |
+
exp = Period("2011-04-02", freq="D")
|
376 |
+
assert result == exp
|
377 |
+
|
378 |
+
result = per - offsets.Day(2)
|
379 |
+
exp = Period("2011-03-30", freq="D")
|
380 |
+
assert result == exp
|
381 |
+
|
382 |
+
msg = r"Input cannot be converted to Period\(freq=D\)"
|
383 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
384 |
+
per + offsets.Hour(2)
|
385 |
+
|
386 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
387 |
+
per - offsets.Hour(2)
|
388 |
+
|
389 |
+
def test_period_add_timestamp_raises(self):
|
390 |
+
# GH#17983
|
391 |
+
ts = Timestamp("2017")
|
392 |
+
per = Period("2017", freq="M")
|
393 |
+
|
394 |
+
msg = r"unsupported operand type\(s\) for \+: 'Timestamp' and 'Period'"
|
395 |
+
with pytest.raises(TypeError, match=msg):
|
396 |
+
ts + per
|
397 |
+
|
398 |
+
msg = r"unsupported operand type\(s\) for \+: 'Period' and 'Timestamp'"
|
399 |
+
with pytest.raises(TypeError, match=msg):
|
400 |
+
per + ts
|
401 |
+
|
402 |
+
|
403 |
+
class TestPeriodComparisons:
|
404 |
+
def test_period_comparison_same_freq(self):
|
405 |
+
jan = Period("2000-01", "M")
|
406 |
+
feb = Period("2000-02", "M")
|
407 |
+
|
408 |
+
assert not jan == feb
|
409 |
+
assert jan != feb
|
410 |
+
assert jan < feb
|
411 |
+
assert jan <= feb
|
412 |
+
assert not jan > feb
|
413 |
+
assert not jan >= feb
|
414 |
+
|
415 |
+
def test_period_comparison_same_period_different_object(self):
|
416 |
+
# Separate Period objects for the same period
|
417 |
+
left = Period("2000-01", "M")
|
418 |
+
right = Period("2000-01", "M")
|
419 |
+
|
420 |
+
assert left == right
|
421 |
+
assert left >= right
|
422 |
+
assert left <= right
|
423 |
+
assert not left < right
|
424 |
+
assert not left > right
|
425 |
+
|
426 |
+
def test_period_comparison_mismatched_freq(self):
|
427 |
+
jan = Period("2000-01", "M")
|
428 |
+
day = Period("2012-01-01", "D")
|
429 |
+
|
430 |
+
assert not jan == day
|
431 |
+
assert jan != day
|
432 |
+
msg = r"Input has different freq=D from Period\(freq=M\)"
|
433 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
434 |
+
jan < day
|
435 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
436 |
+
jan <= day
|
437 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
438 |
+
jan > day
|
439 |
+
with pytest.raises(IncompatibleFrequency, match=msg):
|
440 |
+
jan >= day
|
441 |
+
|
442 |
+
def test_period_comparison_invalid_type(self):
|
443 |
+
jan = Period("2000-01", "M")
|
444 |
+
|
445 |
+
assert not jan == 1
|
446 |
+
assert jan != 1
|
447 |
+
|
448 |
+
int_or_per = "'(Period|int)'"
|
449 |
+
msg = f"not supported between instances of {int_or_per} and {int_or_per}"
|
450 |
+
for left, right in [(jan, 1), (1, jan)]:
|
451 |
+
with pytest.raises(TypeError, match=msg):
|
452 |
+
left > right
|
453 |
+
with pytest.raises(TypeError, match=msg):
|
454 |
+
left >= right
|
455 |
+
with pytest.raises(TypeError, match=msg):
|
456 |
+
left < right
|
457 |
+
with pytest.raises(TypeError, match=msg):
|
458 |
+
left <= right
|
459 |
+
|
460 |
+
def test_period_comparison_nat(self):
|
461 |
+
per = Period("2011-01-01", freq="D")
|
462 |
+
|
463 |
+
ts = Timestamp("2011-01-01")
|
464 |
+
# confirm Period('NaT') work identical with Timestamp('NaT')
|
465 |
+
for left, right in [
|
466 |
+
(NaT, per),
|
467 |
+
(per, NaT),
|
468 |
+
(NaT, ts),
|
469 |
+
(ts, NaT),
|
470 |
+
]:
|
471 |
+
assert not left < right
|
472 |
+
assert not left > right
|
473 |
+
assert not left == right
|
474 |
+
assert left != right
|
475 |
+
assert not left <= right
|
476 |
+
assert not left >= right
|
477 |
+
|
478 |
+
@pytest.mark.parametrize(
|
479 |
+
"zerodim_arr, expected",
|
480 |
+
((np.array(0), False), (np.array(Period("2000-01", "M")), True)),
|
481 |
+
)
|
482 |
+
def test_period_comparison_numpy_zerodim_arr(self, zerodim_arr, expected):
|
483 |
+
per = Period("2000-01", "M")
|
484 |
+
|
485 |
+
assert (per == zerodim_arr) is expected
|
486 |
+
assert (zerodim_arr == per) is expected
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/test_na_scalar.py
ADDED
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import (
|
2 |
+
date,
|
3 |
+
time,
|
4 |
+
timedelta,
|
5 |
+
)
|
6 |
+
import pickle
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import pytest
|
10 |
+
|
11 |
+
from pandas._libs.missing import NA
|
12 |
+
|
13 |
+
from pandas.core.dtypes.common import is_scalar
|
14 |
+
|
15 |
+
import pandas as pd
|
16 |
+
import pandas._testing as tm
|
17 |
+
|
18 |
+
|
19 |
+
def test_singleton():
|
20 |
+
assert NA is NA
|
21 |
+
new_NA = type(NA)()
|
22 |
+
assert new_NA is NA
|
23 |
+
|
24 |
+
|
25 |
+
def test_repr():
|
26 |
+
assert repr(NA) == "<NA>"
|
27 |
+
assert str(NA) == "<NA>"
|
28 |
+
|
29 |
+
|
30 |
+
def test_format():
|
31 |
+
# GH-34740
|
32 |
+
assert format(NA) == "<NA>"
|
33 |
+
assert format(NA, ">10") == " <NA>"
|
34 |
+
assert format(NA, "xxx") == "<NA>" # NA is flexible, accept any format spec
|
35 |
+
|
36 |
+
assert f"{NA}" == "<NA>"
|
37 |
+
assert f"{NA:>10}" == " <NA>"
|
38 |
+
assert f"{NA:xxx}" == "<NA>"
|
39 |
+
|
40 |
+
|
41 |
+
def test_truthiness():
|
42 |
+
msg = "boolean value of NA is ambiguous"
|
43 |
+
|
44 |
+
with pytest.raises(TypeError, match=msg):
|
45 |
+
bool(NA)
|
46 |
+
|
47 |
+
with pytest.raises(TypeError, match=msg):
|
48 |
+
not NA
|
49 |
+
|
50 |
+
|
51 |
+
def test_hashable():
|
52 |
+
assert hash(NA) == hash(NA)
|
53 |
+
d = {NA: "test"}
|
54 |
+
assert d[NA] == "test"
|
55 |
+
|
56 |
+
|
57 |
+
@pytest.mark.parametrize(
|
58 |
+
"other", [NA, 1, 1.0, "a", b"a", np.int64(1), np.nan], ids=repr
|
59 |
+
)
|
60 |
+
def test_arithmetic_ops(all_arithmetic_functions, other):
|
61 |
+
op = all_arithmetic_functions
|
62 |
+
|
63 |
+
if op.__name__ in ("pow", "rpow", "rmod") and isinstance(other, (str, bytes)):
|
64 |
+
pytest.skip(reason=f"{op.__name__} with NA and {other} not defined.")
|
65 |
+
if op.__name__ in ("divmod", "rdivmod"):
|
66 |
+
assert op(NA, other) is (NA, NA)
|
67 |
+
else:
|
68 |
+
if op.__name__ == "rpow":
|
69 |
+
# avoid special case
|
70 |
+
other += 1
|
71 |
+
assert op(NA, other) is NA
|
72 |
+
|
73 |
+
|
74 |
+
@pytest.mark.parametrize(
|
75 |
+
"other",
|
76 |
+
[
|
77 |
+
NA,
|
78 |
+
1,
|
79 |
+
1.0,
|
80 |
+
"a",
|
81 |
+
b"a",
|
82 |
+
np.int64(1),
|
83 |
+
np.nan,
|
84 |
+
np.bool_(True),
|
85 |
+
time(0),
|
86 |
+
date(1, 2, 3),
|
87 |
+
timedelta(1),
|
88 |
+
pd.NaT,
|
89 |
+
],
|
90 |
+
)
|
91 |
+
def test_comparison_ops(comparison_op, other):
|
92 |
+
assert comparison_op(NA, other) is NA
|
93 |
+
assert comparison_op(other, NA) is NA
|
94 |
+
|
95 |
+
|
96 |
+
@pytest.mark.parametrize(
|
97 |
+
"value",
|
98 |
+
[
|
99 |
+
0,
|
100 |
+
0.0,
|
101 |
+
-0,
|
102 |
+
-0.0,
|
103 |
+
False,
|
104 |
+
np.bool_(False),
|
105 |
+
np.int_(0),
|
106 |
+
np.float64(0),
|
107 |
+
np.int_(-0),
|
108 |
+
np.float64(-0),
|
109 |
+
],
|
110 |
+
)
|
111 |
+
@pytest.mark.parametrize("asarray", [True, False])
|
112 |
+
def test_pow_special(value, asarray):
|
113 |
+
if asarray:
|
114 |
+
value = np.array([value])
|
115 |
+
result = NA**value
|
116 |
+
|
117 |
+
if asarray:
|
118 |
+
result = result[0]
|
119 |
+
else:
|
120 |
+
# this assertion isn't possible for ndarray.
|
121 |
+
assert isinstance(result, type(value))
|
122 |
+
assert result == 1
|
123 |
+
|
124 |
+
|
125 |
+
@pytest.mark.parametrize(
|
126 |
+
"value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float64(1)]
|
127 |
+
)
|
128 |
+
@pytest.mark.parametrize("asarray", [True, False])
|
129 |
+
def test_rpow_special(value, asarray):
|
130 |
+
if asarray:
|
131 |
+
value = np.array([value])
|
132 |
+
result = value**NA
|
133 |
+
|
134 |
+
if asarray:
|
135 |
+
result = result[0]
|
136 |
+
elif not isinstance(value, (np.float64, np.bool_, np.int_)):
|
137 |
+
# this assertion isn't possible with asarray=True
|
138 |
+
assert isinstance(result, type(value))
|
139 |
+
|
140 |
+
assert result == value
|
141 |
+
|
142 |
+
|
143 |
+
@pytest.mark.parametrize("value", [-1, -1.0, np.int_(-1), np.float64(-1)])
|
144 |
+
@pytest.mark.parametrize("asarray", [True, False])
|
145 |
+
def test_rpow_minus_one(value, asarray):
|
146 |
+
if asarray:
|
147 |
+
value = np.array([value])
|
148 |
+
result = value**NA
|
149 |
+
|
150 |
+
if asarray:
|
151 |
+
result = result[0]
|
152 |
+
|
153 |
+
assert pd.isna(result)
|
154 |
+
|
155 |
+
|
156 |
+
def test_unary_ops():
|
157 |
+
assert +NA is NA
|
158 |
+
assert -NA is NA
|
159 |
+
assert abs(NA) is NA
|
160 |
+
assert ~NA is NA
|
161 |
+
|
162 |
+
|
163 |
+
def test_logical_and():
|
164 |
+
assert NA & True is NA
|
165 |
+
assert True & NA is NA
|
166 |
+
assert NA & False is False
|
167 |
+
assert False & NA is False
|
168 |
+
assert NA & NA is NA
|
169 |
+
|
170 |
+
msg = "unsupported operand type"
|
171 |
+
with pytest.raises(TypeError, match=msg):
|
172 |
+
NA & 5
|
173 |
+
|
174 |
+
|
175 |
+
def test_logical_or():
|
176 |
+
assert NA | True is True
|
177 |
+
assert True | NA is True
|
178 |
+
assert NA | False is NA
|
179 |
+
assert False | NA is NA
|
180 |
+
assert NA | NA is NA
|
181 |
+
|
182 |
+
msg = "unsupported operand type"
|
183 |
+
with pytest.raises(TypeError, match=msg):
|
184 |
+
NA | 5
|
185 |
+
|
186 |
+
|
187 |
+
def test_logical_xor():
|
188 |
+
assert NA ^ True is NA
|
189 |
+
assert True ^ NA is NA
|
190 |
+
assert NA ^ False is NA
|
191 |
+
assert False ^ NA is NA
|
192 |
+
assert NA ^ NA is NA
|
193 |
+
|
194 |
+
msg = "unsupported operand type"
|
195 |
+
with pytest.raises(TypeError, match=msg):
|
196 |
+
NA ^ 5
|
197 |
+
|
198 |
+
|
199 |
+
def test_logical_not():
|
200 |
+
assert ~NA is NA
|
201 |
+
|
202 |
+
|
203 |
+
@pytest.mark.parametrize("shape", [(3,), (3, 3), (1, 2, 3)])
|
204 |
+
def test_arithmetic_ndarray(shape, all_arithmetic_functions):
|
205 |
+
op = all_arithmetic_functions
|
206 |
+
a = np.zeros(shape)
|
207 |
+
if op.__name__ == "pow":
|
208 |
+
a += 5
|
209 |
+
result = op(NA, a)
|
210 |
+
expected = np.full(a.shape, NA, dtype=object)
|
211 |
+
tm.assert_numpy_array_equal(result, expected)
|
212 |
+
|
213 |
+
|
214 |
+
def test_is_scalar():
|
215 |
+
assert is_scalar(NA) is True
|
216 |
+
|
217 |
+
|
218 |
+
def test_isna():
|
219 |
+
assert pd.isna(NA) is True
|
220 |
+
assert pd.notna(NA) is False
|
221 |
+
|
222 |
+
|
223 |
+
def test_series_isna():
|
224 |
+
s = pd.Series([1, NA], dtype=object)
|
225 |
+
expected = pd.Series([False, True])
|
226 |
+
tm.assert_series_equal(s.isna(), expected)
|
227 |
+
|
228 |
+
|
229 |
+
def test_ufunc():
|
230 |
+
assert np.log(NA) is NA
|
231 |
+
assert np.add(NA, 1) is NA
|
232 |
+
result = np.divmod(NA, 1)
|
233 |
+
assert result[0] is NA and result[1] is NA
|
234 |
+
|
235 |
+
result = np.frexp(NA)
|
236 |
+
assert result[0] is NA and result[1] is NA
|
237 |
+
|
238 |
+
|
239 |
+
def test_ufunc_raises():
|
240 |
+
msg = "ufunc method 'at'"
|
241 |
+
with pytest.raises(ValueError, match=msg):
|
242 |
+
np.log.at(NA, 0)
|
243 |
+
|
244 |
+
|
245 |
+
def test_binary_input_not_dunder():
|
246 |
+
a = np.array([1, 2, 3])
|
247 |
+
expected = np.array([NA, NA, NA], dtype=object)
|
248 |
+
result = np.logaddexp(a, NA)
|
249 |
+
tm.assert_numpy_array_equal(result, expected)
|
250 |
+
|
251 |
+
result = np.logaddexp(NA, a)
|
252 |
+
tm.assert_numpy_array_equal(result, expected)
|
253 |
+
|
254 |
+
# all NA, multiple inputs
|
255 |
+
assert np.logaddexp(NA, NA) is NA
|
256 |
+
|
257 |
+
result = np.modf(NA, NA)
|
258 |
+
assert len(result) == 2
|
259 |
+
assert all(x is NA for x in result)
|
260 |
+
|
261 |
+
|
262 |
+
def test_divmod_ufunc():
|
263 |
+
# binary in, binary out.
|
264 |
+
a = np.array([1, 2, 3])
|
265 |
+
expected = np.array([NA, NA, NA], dtype=object)
|
266 |
+
|
267 |
+
result = np.divmod(a, NA)
|
268 |
+
assert isinstance(result, tuple)
|
269 |
+
for arr in result:
|
270 |
+
tm.assert_numpy_array_equal(arr, expected)
|
271 |
+
tm.assert_numpy_array_equal(arr, expected)
|
272 |
+
|
273 |
+
result = np.divmod(NA, a)
|
274 |
+
for arr in result:
|
275 |
+
tm.assert_numpy_array_equal(arr, expected)
|
276 |
+
tm.assert_numpy_array_equal(arr, expected)
|
277 |
+
|
278 |
+
|
279 |
+
def test_integer_hash_collision_dict():
|
280 |
+
# GH 30013
|
281 |
+
result = {NA: "foo", hash(NA): "bar"}
|
282 |
+
|
283 |
+
assert result[NA] == "foo"
|
284 |
+
assert result[hash(NA)] == "bar"
|
285 |
+
|
286 |
+
|
287 |
+
def test_integer_hash_collision_set():
|
288 |
+
# GH 30013
|
289 |
+
result = {NA, hash(NA)}
|
290 |
+
|
291 |
+
assert len(result) == 2
|
292 |
+
assert NA in result
|
293 |
+
assert hash(NA) in result
|
294 |
+
|
295 |
+
|
296 |
+
def test_pickle_roundtrip():
|
297 |
+
# https://github.com/pandas-dev/pandas/issues/31847
|
298 |
+
result = pickle.loads(pickle.dumps(NA))
|
299 |
+
assert result is NA
|
300 |
+
|
301 |
+
|
302 |
+
def test_pickle_roundtrip_pandas():
|
303 |
+
result = tm.round_trip_pickle(NA)
|
304 |
+
assert result is NA
|
305 |
+
|
306 |
+
|
307 |
+
@pytest.mark.parametrize(
|
308 |
+
"values, dtype", [([1, 2, NA], "Int64"), (["A", "B", NA], "string")]
|
309 |
+
)
|
310 |
+
@pytest.mark.parametrize("as_frame", [True, False])
|
311 |
+
def test_pickle_roundtrip_containers(as_frame, values, dtype):
|
312 |
+
s = pd.Series(pd.array(values, dtype=dtype))
|
313 |
+
if as_frame:
|
314 |
+
s = s.to_frame(name="A")
|
315 |
+
result = tm.round_trip_pickle(s)
|
316 |
+
tm.assert_equal(result, s)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/test_nat.py
ADDED
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import (
|
2 |
+
datetime,
|
3 |
+
timedelta,
|
4 |
+
)
|
5 |
+
import operator
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
import pytest
|
9 |
+
import pytz
|
10 |
+
|
11 |
+
from pandas._libs.tslibs import iNaT
|
12 |
+
from pandas.compat.numpy import np_version_gte1p24p3
|
13 |
+
|
14 |
+
from pandas import (
|
15 |
+
DatetimeIndex,
|
16 |
+
DatetimeTZDtype,
|
17 |
+
Index,
|
18 |
+
NaT,
|
19 |
+
Period,
|
20 |
+
Series,
|
21 |
+
Timedelta,
|
22 |
+
TimedeltaIndex,
|
23 |
+
Timestamp,
|
24 |
+
isna,
|
25 |
+
offsets,
|
26 |
+
)
|
27 |
+
import pandas._testing as tm
|
28 |
+
from pandas.core import roperator
|
29 |
+
from pandas.core.arrays import (
|
30 |
+
DatetimeArray,
|
31 |
+
PeriodArray,
|
32 |
+
TimedeltaArray,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
class TestNaTFormatting:
|
37 |
+
def test_repr(self):
|
38 |
+
assert repr(NaT) == "NaT"
|
39 |
+
|
40 |
+
def test_str(self):
|
41 |
+
assert str(NaT) == "NaT"
|
42 |
+
|
43 |
+
def test_isoformat(self):
|
44 |
+
assert NaT.isoformat() == "NaT"
|
45 |
+
|
46 |
+
|
47 |
+
@pytest.mark.parametrize(
|
48 |
+
"nat,idx",
|
49 |
+
[
|
50 |
+
(Timestamp("NaT"), DatetimeArray),
|
51 |
+
(Timedelta("NaT"), TimedeltaArray),
|
52 |
+
(Period("NaT", freq="M"), PeriodArray),
|
53 |
+
],
|
54 |
+
)
|
55 |
+
def test_nat_fields(nat, idx):
|
56 |
+
for field in idx._field_ops:
|
57 |
+
# weekday is a property of DTI, but a method
|
58 |
+
# on NaT/Timestamp for compat with datetime
|
59 |
+
if field == "weekday":
|
60 |
+
continue
|
61 |
+
|
62 |
+
result = getattr(NaT, field)
|
63 |
+
assert np.isnan(result)
|
64 |
+
|
65 |
+
result = getattr(nat, field)
|
66 |
+
assert np.isnan(result)
|
67 |
+
|
68 |
+
for field in idx._bool_ops:
|
69 |
+
result = getattr(NaT, field)
|
70 |
+
assert result is False
|
71 |
+
|
72 |
+
result = getattr(nat, field)
|
73 |
+
assert result is False
|
74 |
+
|
75 |
+
|
76 |
+
def test_nat_vector_field_access():
|
77 |
+
idx = DatetimeIndex(["1/1/2000", None, None, "1/4/2000"])
|
78 |
+
|
79 |
+
for field in DatetimeArray._field_ops:
|
80 |
+
# weekday is a property of DTI, but a method
|
81 |
+
# on NaT/Timestamp for compat with datetime
|
82 |
+
if field == "weekday":
|
83 |
+
continue
|
84 |
+
|
85 |
+
result = getattr(idx, field)
|
86 |
+
expected = Index([getattr(x, field) for x in idx])
|
87 |
+
tm.assert_index_equal(result, expected)
|
88 |
+
|
89 |
+
ser = Series(idx)
|
90 |
+
|
91 |
+
for field in DatetimeArray._field_ops:
|
92 |
+
# weekday is a property of DTI, but a method
|
93 |
+
# on NaT/Timestamp for compat with datetime
|
94 |
+
if field == "weekday":
|
95 |
+
continue
|
96 |
+
|
97 |
+
result = getattr(ser.dt, field)
|
98 |
+
expected = [getattr(x, field) for x in idx]
|
99 |
+
tm.assert_series_equal(result, Series(expected))
|
100 |
+
|
101 |
+
for field in DatetimeArray._bool_ops:
|
102 |
+
result = getattr(ser.dt, field)
|
103 |
+
expected = [getattr(x, field) for x in idx]
|
104 |
+
tm.assert_series_equal(result, Series(expected))
|
105 |
+
|
106 |
+
|
107 |
+
@pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period])
|
108 |
+
@pytest.mark.parametrize(
|
109 |
+
"value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat", "", "NAT"]
|
110 |
+
)
|
111 |
+
def test_identity(klass, value):
|
112 |
+
assert klass(value) is NaT
|
113 |
+
|
114 |
+
|
115 |
+
@pytest.mark.parametrize("klass", [Timestamp, Timedelta])
|
116 |
+
@pytest.mark.parametrize("method", ["round", "floor", "ceil"])
|
117 |
+
@pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])
|
118 |
+
def test_round_nat(klass, method, freq):
|
119 |
+
# see gh-14940
|
120 |
+
ts = klass("nat")
|
121 |
+
|
122 |
+
round_method = getattr(ts, method)
|
123 |
+
assert round_method(freq) is ts
|
124 |
+
|
125 |
+
|
126 |
+
@pytest.mark.parametrize(
|
127 |
+
"method",
|
128 |
+
[
|
129 |
+
"astimezone",
|
130 |
+
"combine",
|
131 |
+
"ctime",
|
132 |
+
"dst",
|
133 |
+
"fromordinal",
|
134 |
+
"fromtimestamp",
|
135 |
+
"fromisocalendar",
|
136 |
+
"isocalendar",
|
137 |
+
"strftime",
|
138 |
+
"strptime",
|
139 |
+
"time",
|
140 |
+
"timestamp",
|
141 |
+
"timetuple",
|
142 |
+
"timetz",
|
143 |
+
"toordinal",
|
144 |
+
"tzname",
|
145 |
+
"utcfromtimestamp",
|
146 |
+
"utcnow",
|
147 |
+
"utcoffset",
|
148 |
+
"utctimetuple",
|
149 |
+
"timestamp",
|
150 |
+
],
|
151 |
+
)
|
152 |
+
def test_nat_methods_raise(method):
|
153 |
+
# see gh-9513, gh-17329
|
154 |
+
msg = f"NaTType does not support {method}"
|
155 |
+
|
156 |
+
with pytest.raises(ValueError, match=msg):
|
157 |
+
getattr(NaT, method)()
|
158 |
+
|
159 |
+
|
160 |
+
@pytest.mark.parametrize("method", ["weekday", "isoweekday"])
|
161 |
+
def test_nat_methods_nan(method):
|
162 |
+
# see gh-9513, gh-17329
|
163 |
+
assert np.isnan(getattr(NaT, method)())
|
164 |
+
|
165 |
+
|
166 |
+
@pytest.mark.parametrize(
|
167 |
+
"method", ["date", "now", "replace", "today", "tz_convert", "tz_localize"]
|
168 |
+
)
|
169 |
+
def test_nat_methods_nat(method):
|
170 |
+
# see gh-8254, gh-9513, gh-17329
|
171 |
+
assert getattr(NaT, method)() is NaT
|
172 |
+
|
173 |
+
|
174 |
+
@pytest.mark.parametrize(
|
175 |
+
"get_nat", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)]
|
176 |
+
)
|
177 |
+
def test_nat_iso_format(get_nat):
|
178 |
+
# see gh-12300
|
179 |
+
assert get_nat("NaT").isoformat() == "NaT"
|
180 |
+
assert get_nat("NaT").isoformat(timespec="nanoseconds") == "NaT"
|
181 |
+
|
182 |
+
|
183 |
+
@pytest.mark.parametrize(
|
184 |
+
"klass,expected",
|
185 |
+
[
|
186 |
+
(Timestamp, ["normalize", "to_julian_date", "to_period", "unit"]),
|
187 |
+
(
|
188 |
+
Timedelta,
|
189 |
+
[
|
190 |
+
"components",
|
191 |
+
"resolution_string",
|
192 |
+
"to_pytimedelta",
|
193 |
+
"to_timedelta64",
|
194 |
+
"unit",
|
195 |
+
"view",
|
196 |
+
],
|
197 |
+
),
|
198 |
+
],
|
199 |
+
)
|
200 |
+
def test_missing_public_nat_methods(klass, expected):
|
201 |
+
# see gh-17327
|
202 |
+
#
|
203 |
+
# NaT should have *most* of the Timestamp and Timedelta methods.
|
204 |
+
# Here, we check which public methods NaT does not have. We
|
205 |
+
# ignore any missing private methods.
|
206 |
+
nat_names = dir(NaT)
|
207 |
+
klass_names = dir(klass)
|
208 |
+
|
209 |
+
missing = [x for x in klass_names if x not in nat_names and not x.startswith("_")]
|
210 |
+
missing.sort()
|
211 |
+
|
212 |
+
assert missing == expected
|
213 |
+
|
214 |
+
|
215 |
+
def _get_overlap_public_nat_methods(klass, as_tuple=False):
|
216 |
+
"""
|
217 |
+
Get overlapping public methods between NaT and another class.
|
218 |
+
|
219 |
+
Parameters
|
220 |
+
----------
|
221 |
+
klass : type
|
222 |
+
The class to compare with NaT
|
223 |
+
as_tuple : bool, default False
|
224 |
+
Whether to return a list of tuples of the form (klass, method).
|
225 |
+
|
226 |
+
Returns
|
227 |
+
-------
|
228 |
+
overlap : list
|
229 |
+
"""
|
230 |
+
nat_names = dir(NaT)
|
231 |
+
klass_names = dir(klass)
|
232 |
+
|
233 |
+
overlap = [
|
234 |
+
x
|
235 |
+
for x in nat_names
|
236 |
+
if x in klass_names and not x.startswith("_") and callable(getattr(klass, x))
|
237 |
+
]
|
238 |
+
|
239 |
+
# Timestamp takes precedence over Timedelta in terms of overlap.
|
240 |
+
if klass is Timedelta:
|
241 |
+
ts_names = dir(Timestamp)
|
242 |
+
overlap = [x for x in overlap if x not in ts_names]
|
243 |
+
|
244 |
+
if as_tuple:
|
245 |
+
overlap = [(klass, method) for method in overlap]
|
246 |
+
|
247 |
+
overlap.sort()
|
248 |
+
return overlap
|
249 |
+
|
250 |
+
|
251 |
+
@pytest.mark.parametrize(
|
252 |
+
"klass,expected",
|
253 |
+
[
|
254 |
+
(
|
255 |
+
Timestamp,
|
256 |
+
[
|
257 |
+
"as_unit",
|
258 |
+
"astimezone",
|
259 |
+
"ceil",
|
260 |
+
"combine",
|
261 |
+
"ctime",
|
262 |
+
"date",
|
263 |
+
"day_name",
|
264 |
+
"dst",
|
265 |
+
"floor",
|
266 |
+
"fromisocalendar",
|
267 |
+
"fromisoformat",
|
268 |
+
"fromordinal",
|
269 |
+
"fromtimestamp",
|
270 |
+
"isocalendar",
|
271 |
+
"isoformat",
|
272 |
+
"isoweekday",
|
273 |
+
"month_name",
|
274 |
+
"now",
|
275 |
+
"replace",
|
276 |
+
"round",
|
277 |
+
"strftime",
|
278 |
+
"strptime",
|
279 |
+
"time",
|
280 |
+
"timestamp",
|
281 |
+
"timetuple",
|
282 |
+
"timetz",
|
283 |
+
"to_datetime64",
|
284 |
+
"to_numpy",
|
285 |
+
"to_pydatetime",
|
286 |
+
"today",
|
287 |
+
"toordinal",
|
288 |
+
"tz_convert",
|
289 |
+
"tz_localize",
|
290 |
+
"tzname",
|
291 |
+
"utcfromtimestamp",
|
292 |
+
"utcnow",
|
293 |
+
"utcoffset",
|
294 |
+
"utctimetuple",
|
295 |
+
"weekday",
|
296 |
+
],
|
297 |
+
),
|
298 |
+
(Timedelta, ["total_seconds"]),
|
299 |
+
],
|
300 |
+
)
|
301 |
+
def test_overlap_public_nat_methods(klass, expected):
|
302 |
+
# see gh-17327
|
303 |
+
#
|
304 |
+
# NaT should have *most* of the Timestamp and Timedelta methods.
|
305 |
+
# In case when Timestamp, Timedelta, and NaT are overlap, the overlap
|
306 |
+
# is considered to be with Timestamp and NaT, not Timedelta.
|
307 |
+
assert _get_overlap_public_nat_methods(klass) == expected
|
308 |
+
|
309 |
+
|
310 |
+
@pytest.mark.parametrize(
|
311 |
+
"compare",
|
312 |
+
(
|
313 |
+
_get_overlap_public_nat_methods(Timestamp, True)
|
314 |
+
+ _get_overlap_public_nat_methods(Timedelta, True)
|
315 |
+
),
|
316 |
+
ids=lambda x: f"{x[0].__name__}.{x[1]}",
|
317 |
+
)
|
318 |
+
def test_nat_doc_strings(compare):
|
319 |
+
# see gh-17327
|
320 |
+
#
|
321 |
+
# The docstrings for overlapping methods should match.
|
322 |
+
klass, method = compare
|
323 |
+
klass_doc = getattr(klass, method).__doc__
|
324 |
+
|
325 |
+
if klass == Timestamp and method == "isoformat":
|
326 |
+
pytest.skip(
|
327 |
+
"Ignore differences with Timestamp.isoformat() as they're intentional"
|
328 |
+
)
|
329 |
+
|
330 |
+
if method == "to_numpy":
|
331 |
+
# GH#44460 can return either dt64 or td64 depending on dtype,
|
332 |
+
# different docstring is intentional
|
333 |
+
pytest.skip(f"different docstring for {method} is intentional")
|
334 |
+
|
335 |
+
nat_doc = getattr(NaT, method).__doc__
|
336 |
+
assert klass_doc == nat_doc
|
337 |
+
|
338 |
+
|
339 |
+
_ops = {
|
340 |
+
"left_plus_right": lambda a, b: a + b,
|
341 |
+
"right_plus_left": lambda a, b: b + a,
|
342 |
+
"left_minus_right": lambda a, b: a - b,
|
343 |
+
"right_minus_left": lambda a, b: b - a,
|
344 |
+
"left_times_right": lambda a, b: a * b,
|
345 |
+
"right_times_left": lambda a, b: b * a,
|
346 |
+
"left_div_right": lambda a, b: a / b,
|
347 |
+
"right_div_left": lambda a, b: b / a,
|
348 |
+
}
|
349 |
+
|
350 |
+
|
351 |
+
@pytest.mark.parametrize("op_name", list(_ops.keys()))
|
352 |
+
@pytest.mark.parametrize(
|
353 |
+
"value,val_type",
|
354 |
+
[
|
355 |
+
(2, "scalar"),
|
356 |
+
(1.5, "floating"),
|
357 |
+
(np.nan, "floating"),
|
358 |
+
("foo", "str"),
|
359 |
+
(timedelta(3600), "timedelta"),
|
360 |
+
(Timedelta("5s"), "timedelta"),
|
361 |
+
(datetime(2014, 1, 1), "timestamp"),
|
362 |
+
(Timestamp("2014-01-01"), "timestamp"),
|
363 |
+
(Timestamp("2014-01-01", tz="UTC"), "timestamp"),
|
364 |
+
(Timestamp("2014-01-01", tz="US/Eastern"), "timestamp"),
|
365 |
+
(pytz.timezone("Asia/Tokyo").localize(datetime(2014, 1, 1)), "timestamp"),
|
366 |
+
],
|
367 |
+
)
|
368 |
+
def test_nat_arithmetic_scalar(op_name, value, val_type):
|
369 |
+
# see gh-6873
|
370 |
+
invalid_ops = {
|
371 |
+
"scalar": {"right_div_left"},
|
372 |
+
"floating": {
|
373 |
+
"right_div_left",
|
374 |
+
"left_minus_right",
|
375 |
+
"right_minus_left",
|
376 |
+
"left_plus_right",
|
377 |
+
"right_plus_left",
|
378 |
+
},
|
379 |
+
"str": set(_ops.keys()),
|
380 |
+
"timedelta": {"left_times_right", "right_times_left"},
|
381 |
+
"timestamp": {
|
382 |
+
"left_times_right",
|
383 |
+
"right_times_left",
|
384 |
+
"left_div_right",
|
385 |
+
"right_div_left",
|
386 |
+
},
|
387 |
+
}
|
388 |
+
|
389 |
+
op = _ops[op_name]
|
390 |
+
|
391 |
+
if op_name in invalid_ops.get(val_type, set()):
|
392 |
+
if (
|
393 |
+
val_type == "timedelta"
|
394 |
+
and "times" in op_name
|
395 |
+
and isinstance(value, Timedelta)
|
396 |
+
):
|
397 |
+
typs = "(Timedelta|NaTType)"
|
398 |
+
msg = rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'"
|
399 |
+
elif val_type == "str":
|
400 |
+
# un-specific check here because the message comes from str
|
401 |
+
# and varies by method
|
402 |
+
msg = "|".join(
|
403 |
+
[
|
404 |
+
"can only concatenate str",
|
405 |
+
"unsupported operand type",
|
406 |
+
"can't multiply sequence",
|
407 |
+
"Can't convert 'NaTType'",
|
408 |
+
"must be str, not NaTType",
|
409 |
+
]
|
410 |
+
)
|
411 |
+
else:
|
412 |
+
msg = "unsupported operand type"
|
413 |
+
|
414 |
+
with pytest.raises(TypeError, match=msg):
|
415 |
+
op(NaT, value)
|
416 |
+
else:
|
417 |
+
if val_type == "timedelta" and "div" in op_name:
|
418 |
+
expected = np.nan
|
419 |
+
else:
|
420 |
+
expected = NaT
|
421 |
+
|
422 |
+
assert op(NaT, value) is expected
|
423 |
+
|
424 |
+
|
425 |
+
@pytest.mark.parametrize(
|
426 |
+
"val,expected", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64("NaT"), np.nan)]
|
427 |
+
)
|
428 |
+
def test_nat_rfloordiv_timedelta(val, expected):
|
429 |
+
# see gh-#18846
|
430 |
+
#
|
431 |
+
# See also test_timedelta.TestTimedeltaArithmetic.test_floordiv
|
432 |
+
td = Timedelta(hours=3, minutes=4)
|
433 |
+
assert td // val is expected
|
434 |
+
|
435 |
+
|
436 |
+
@pytest.mark.parametrize(
|
437 |
+
"op_name",
|
438 |
+
["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],
|
439 |
+
)
|
440 |
+
@pytest.mark.parametrize(
|
441 |
+
"value",
|
442 |
+
[
|
443 |
+
DatetimeIndex(["2011-01-01", "2011-01-02"], name="x"),
|
444 |
+
DatetimeIndex(["2011-01-01", "2011-01-02"], tz="US/Eastern", name="x"),
|
445 |
+
DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"], dtype="M8[ns]"),
|
446 |
+
DatetimeArray._from_sequence(
|
447 |
+
["2011-01-01", "2011-01-02"], dtype=DatetimeTZDtype(tz="US/Pacific")
|
448 |
+
),
|
449 |
+
TimedeltaIndex(["1 day", "2 day"], name="x"),
|
450 |
+
],
|
451 |
+
)
|
452 |
+
def test_nat_arithmetic_index(op_name, value):
|
453 |
+
# see gh-11718
|
454 |
+
exp_name = "x"
|
455 |
+
exp_data = [NaT] * 2
|
456 |
+
|
457 |
+
if value.dtype.kind == "M" and "plus" in op_name:
|
458 |
+
expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name)
|
459 |
+
else:
|
460 |
+
expected = TimedeltaIndex(exp_data, name=exp_name)
|
461 |
+
expected = expected.as_unit(value.unit)
|
462 |
+
|
463 |
+
if not isinstance(value, Index):
|
464 |
+
expected = expected.array
|
465 |
+
|
466 |
+
op = _ops[op_name]
|
467 |
+
result = op(NaT, value)
|
468 |
+
tm.assert_equal(result, expected)
|
469 |
+
|
470 |
+
|
471 |
+
@pytest.mark.parametrize(
|
472 |
+
"op_name",
|
473 |
+
["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"],
|
474 |
+
)
|
475 |
+
@pytest.mark.parametrize("box", [TimedeltaIndex, Series, TimedeltaArray._from_sequence])
|
476 |
+
def test_nat_arithmetic_td64_vector(op_name, box):
|
477 |
+
# see gh-19124
|
478 |
+
vec = box(["1 day", "2 day"], dtype="timedelta64[ns]")
|
479 |
+
box_nat = box([NaT, NaT], dtype="timedelta64[ns]")
|
480 |
+
tm.assert_equal(_ops[op_name](vec, NaT), box_nat)
|
481 |
+
|
482 |
+
|
483 |
+
@pytest.mark.parametrize(
|
484 |
+
"dtype,op,out_dtype",
|
485 |
+
[
|
486 |
+
("datetime64[ns]", operator.add, "datetime64[ns]"),
|
487 |
+
("datetime64[ns]", roperator.radd, "datetime64[ns]"),
|
488 |
+
("datetime64[ns]", operator.sub, "timedelta64[ns]"),
|
489 |
+
("datetime64[ns]", roperator.rsub, "timedelta64[ns]"),
|
490 |
+
("timedelta64[ns]", operator.add, "datetime64[ns]"),
|
491 |
+
("timedelta64[ns]", roperator.radd, "datetime64[ns]"),
|
492 |
+
("timedelta64[ns]", operator.sub, "datetime64[ns]"),
|
493 |
+
("timedelta64[ns]", roperator.rsub, "timedelta64[ns]"),
|
494 |
+
],
|
495 |
+
)
|
496 |
+
def test_nat_arithmetic_ndarray(dtype, op, out_dtype):
|
497 |
+
other = np.arange(10).astype(dtype)
|
498 |
+
result = op(NaT, other)
|
499 |
+
|
500 |
+
expected = np.empty(other.shape, dtype=out_dtype)
|
501 |
+
expected.fill("NaT")
|
502 |
+
tm.assert_numpy_array_equal(result, expected)
|
503 |
+
|
504 |
+
|
505 |
+
def test_nat_pinned_docstrings():
|
506 |
+
# see gh-17327
|
507 |
+
assert NaT.ctime.__doc__ == Timestamp.ctime.__doc__
|
508 |
+
|
509 |
+
|
510 |
+
def test_to_numpy_alias():
|
511 |
+
# GH 24653: alias .to_numpy() for scalars
|
512 |
+
expected = NaT.to_datetime64()
|
513 |
+
result = NaT.to_numpy()
|
514 |
+
|
515 |
+
assert isna(expected) and isna(result)
|
516 |
+
|
517 |
+
# GH#44460
|
518 |
+
result = NaT.to_numpy("M8[s]")
|
519 |
+
assert isinstance(result, np.datetime64)
|
520 |
+
assert result.dtype == "M8[s]"
|
521 |
+
|
522 |
+
result = NaT.to_numpy("m8[ns]")
|
523 |
+
assert isinstance(result, np.timedelta64)
|
524 |
+
assert result.dtype == "m8[ns]"
|
525 |
+
|
526 |
+
result = NaT.to_numpy("m8[s]")
|
527 |
+
assert isinstance(result, np.timedelta64)
|
528 |
+
assert result.dtype == "m8[s]"
|
529 |
+
|
530 |
+
with pytest.raises(ValueError, match="NaT.to_numpy dtype must be a "):
|
531 |
+
NaT.to_numpy(np.int64)
|
532 |
+
|
533 |
+
|
534 |
+
@pytest.mark.parametrize(
|
535 |
+
"other",
|
536 |
+
[
|
537 |
+
Timedelta(0),
|
538 |
+
Timedelta(0).to_pytimedelta(),
|
539 |
+
pytest.param(
|
540 |
+
Timedelta(0).to_timedelta64(),
|
541 |
+
marks=pytest.mark.xfail(
|
542 |
+
not np_version_gte1p24p3,
|
543 |
+
reason="td64 doesn't return NotImplemented, see numpy#17017",
|
544 |
+
# When this xfail is fixed, test_nat_comparisons_numpy
|
545 |
+
# can be removed.
|
546 |
+
),
|
547 |
+
),
|
548 |
+
Timestamp(0),
|
549 |
+
Timestamp(0).to_pydatetime(),
|
550 |
+
pytest.param(
|
551 |
+
Timestamp(0).to_datetime64(),
|
552 |
+
marks=pytest.mark.xfail(
|
553 |
+
not np_version_gte1p24p3,
|
554 |
+
reason="dt64 doesn't return NotImplemented, see numpy#17017",
|
555 |
+
),
|
556 |
+
),
|
557 |
+
Timestamp(0).tz_localize("UTC"),
|
558 |
+
NaT,
|
559 |
+
],
|
560 |
+
)
|
561 |
+
def test_nat_comparisons(compare_operators_no_eq_ne, other):
|
562 |
+
# GH 26039
|
563 |
+
opname = compare_operators_no_eq_ne
|
564 |
+
|
565 |
+
assert getattr(NaT, opname)(other) is False
|
566 |
+
|
567 |
+
op = getattr(operator, opname.strip("_"))
|
568 |
+
assert op(NaT, other) is False
|
569 |
+
assert op(other, NaT) is False
|
570 |
+
|
571 |
+
|
572 |
+
@pytest.mark.parametrize("other", [np.timedelta64(0, "ns"), np.datetime64("now", "ns")])
|
573 |
+
def test_nat_comparisons_numpy(other):
|
574 |
+
# Once numpy#17017 is fixed and the xfailed cases in test_nat_comparisons
|
575 |
+
# pass, this test can be removed
|
576 |
+
assert not NaT == other
|
577 |
+
assert NaT != other
|
578 |
+
assert not NaT < other
|
579 |
+
assert not NaT > other
|
580 |
+
assert not NaT <= other
|
581 |
+
assert not NaT >= other
|
582 |
+
|
583 |
+
|
584 |
+
@pytest.mark.parametrize("other_and_type", [("foo", "str"), (2, "int"), (2.0, "float")])
|
585 |
+
@pytest.mark.parametrize(
|
586 |
+
"symbol_and_op",
|
587 |
+
[("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt)],
|
588 |
+
)
|
589 |
+
def test_nat_comparisons_invalid(other_and_type, symbol_and_op):
|
590 |
+
# GH#35585
|
591 |
+
other, other_type = other_and_type
|
592 |
+
symbol, op = symbol_and_op
|
593 |
+
|
594 |
+
assert not NaT == other
|
595 |
+
assert not other == NaT
|
596 |
+
|
597 |
+
assert NaT != other
|
598 |
+
assert other != NaT
|
599 |
+
|
600 |
+
msg = f"'{symbol}' not supported between instances of 'NaTType' and '{other_type}'"
|
601 |
+
with pytest.raises(TypeError, match=msg):
|
602 |
+
op(NaT, other)
|
603 |
+
|
604 |
+
msg = f"'{symbol}' not supported between instances of '{other_type}' and 'NaTType'"
|
605 |
+
with pytest.raises(TypeError, match=msg):
|
606 |
+
op(other, NaT)
|
607 |
+
|
608 |
+
|
609 |
+
@pytest.mark.parametrize(
|
610 |
+
"other",
|
611 |
+
[
|
612 |
+
np.array(["foo"] * 2, dtype=object),
|
613 |
+
np.array([2, 3], dtype="int64"),
|
614 |
+
np.array([2.0, 3.5], dtype="float64"),
|
615 |
+
],
|
616 |
+
ids=["str", "int", "float"],
|
617 |
+
)
|
618 |
+
def test_nat_comparisons_invalid_ndarray(other):
|
619 |
+
# GH#40722
|
620 |
+
expected = np.array([False, False])
|
621 |
+
result = NaT == other
|
622 |
+
tm.assert_numpy_array_equal(result, expected)
|
623 |
+
result = other == NaT
|
624 |
+
tm.assert_numpy_array_equal(result, expected)
|
625 |
+
|
626 |
+
expected = np.array([True, True])
|
627 |
+
result = NaT != other
|
628 |
+
tm.assert_numpy_array_equal(result, expected)
|
629 |
+
result = other != NaT
|
630 |
+
tm.assert_numpy_array_equal(result, expected)
|
631 |
+
|
632 |
+
for symbol, op in [
|
633 |
+
("<=", operator.le),
|
634 |
+
("<", operator.lt),
|
635 |
+
(">=", operator.ge),
|
636 |
+
(">", operator.gt),
|
637 |
+
]:
|
638 |
+
msg = f"'{symbol}' not supported between"
|
639 |
+
|
640 |
+
with pytest.raises(TypeError, match=msg):
|
641 |
+
op(NaT, other)
|
642 |
+
|
643 |
+
if other.dtype == np.dtype("object"):
|
644 |
+
# uses the reverse operator, so symbol changes
|
645 |
+
msg = None
|
646 |
+
with pytest.raises(TypeError, match=msg):
|
647 |
+
op(other, NaT)
|
648 |
+
|
649 |
+
|
650 |
+
def test_compare_date(fixed_now_ts):
|
651 |
+
# GH#39151 comparing NaT with date object is deprecated
|
652 |
+
# See also: tests.scalar.timestamps.test_comparisons::test_compare_date
|
653 |
+
|
654 |
+
dt = fixed_now_ts.to_pydatetime().date()
|
655 |
+
|
656 |
+
msg = "Cannot compare NaT with datetime.date object"
|
657 |
+
for left, right in [(NaT, dt), (dt, NaT)]:
|
658 |
+
assert not left == right
|
659 |
+
assert left != right
|
660 |
+
|
661 |
+
with pytest.raises(TypeError, match=msg):
|
662 |
+
left < right
|
663 |
+
with pytest.raises(TypeError, match=msg):
|
664 |
+
left <= right
|
665 |
+
with pytest.raises(TypeError, match=msg):
|
666 |
+
left > right
|
667 |
+
with pytest.raises(TypeError, match=msg):
|
668 |
+
left >= right
|
669 |
+
|
670 |
+
|
671 |
+
@pytest.mark.parametrize(
|
672 |
+
"obj",
|
673 |
+
[
|
674 |
+
offsets.YearEnd(2),
|
675 |
+
offsets.YearBegin(2),
|
676 |
+
offsets.MonthBegin(1),
|
677 |
+
offsets.MonthEnd(2),
|
678 |
+
offsets.MonthEnd(12),
|
679 |
+
offsets.Day(2),
|
680 |
+
offsets.Day(5),
|
681 |
+
offsets.Hour(24),
|
682 |
+
offsets.Hour(3),
|
683 |
+
offsets.Minute(),
|
684 |
+
np.timedelta64(3, "h"),
|
685 |
+
np.timedelta64(4, "h"),
|
686 |
+
np.timedelta64(3200, "s"),
|
687 |
+
np.timedelta64(3600, "s"),
|
688 |
+
np.timedelta64(3600 * 24, "s"),
|
689 |
+
np.timedelta64(2, "D"),
|
690 |
+
np.timedelta64(365, "D"),
|
691 |
+
timedelta(-2),
|
692 |
+
timedelta(365),
|
693 |
+
timedelta(minutes=120),
|
694 |
+
timedelta(days=4, minutes=180),
|
695 |
+
timedelta(hours=23),
|
696 |
+
timedelta(hours=23, minutes=30),
|
697 |
+
timedelta(hours=48),
|
698 |
+
],
|
699 |
+
)
|
700 |
+
def test_nat_addsub_tdlike_scalar(obj):
|
701 |
+
assert NaT + obj is NaT
|
702 |
+
assert obj + NaT is NaT
|
703 |
+
assert NaT - obj is NaT
|
704 |
+
|
705 |
+
|
706 |
+
def test_pickle():
|
707 |
+
# GH#4606
|
708 |
+
p = tm.round_trip_pickle(NaT)
|
709 |
+
assert p is NaT
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (202 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-310.pyc
ADDED
Binary file (36.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (17.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (3.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_timedelta.cpython-310.pyc
ADDED
Binary file (20.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (210 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/test_as_unit.cpython-310.pyc
ADDED
Binary file (2.58 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/__pycache__/test_round.cpython-310.pyc
ADDED
Binary file (4.94 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/test_as_unit.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
4 |
+
from pandas.errors import OutOfBoundsTimedelta
|
5 |
+
|
6 |
+
from pandas import Timedelta
|
7 |
+
|
8 |
+
|
9 |
+
class TestAsUnit:
|
10 |
+
def test_as_unit(self):
|
11 |
+
td = Timedelta(days=1)
|
12 |
+
|
13 |
+
assert td.as_unit("ns") is td
|
14 |
+
|
15 |
+
res = td.as_unit("us")
|
16 |
+
assert res._value == td._value // 1000
|
17 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_us.value
|
18 |
+
|
19 |
+
rt = res.as_unit("ns")
|
20 |
+
assert rt._value == td._value
|
21 |
+
assert rt._creso == td._creso
|
22 |
+
|
23 |
+
res = td.as_unit("ms")
|
24 |
+
assert res._value == td._value // 1_000_000
|
25 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
26 |
+
|
27 |
+
rt = res.as_unit("ns")
|
28 |
+
assert rt._value == td._value
|
29 |
+
assert rt._creso == td._creso
|
30 |
+
|
31 |
+
res = td.as_unit("s")
|
32 |
+
assert res._value == td._value // 1_000_000_000
|
33 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_s.value
|
34 |
+
|
35 |
+
rt = res.as_unit("ns")
|
36 |
+
assert rt._value == td._value
|
37 |
+
assert rt._creso == td._creso
|
38 |
+
|
39 |
+
def test_as_unit_overflows(self):
|
40 |
+
# microsecond that would be just out of bounds for nano
|
41 |
+
us = 9223372800000000
|
42 |
+
td = Timedelta._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value)
|
43 |
+
|
44 |
+
msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"
|
45 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
46 |
+
td.as_unit("ns")
|
47 |
+
|
48 |
+
res = td.as_unit("ms")
|
49 |
+
assert res._value == us // 1000
|
50 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
51 |
+
|
52 |
+
def test_as_unit_rounding(self):
|
53 |
+
td = Timedelta(microseconds=1500)
|
54 |
+
res = td.as_unit("ms")
|
55 |
+
|
56 |
+
expected = Timedelta(milliseconds=1)
|
57 |
+
assert res == expected
|
58 |
+
|
59 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
60 |
+
assert res._value == 1
|
61 |
+
|
62 |
+
with pytest.raises(ValueError, match="Cannot losslessly convert units"):
|
63 |
+
td.as_unit("ms", round_ok=False)
|
64 |
+
|
65 |
+
def test_as_unit_non_nano(self):
|
66 |
+
# case where we are going neither to nor from nano
|
67 |
+
td = Timedelta(days=1).as_unit("ms")
|
68 |
+
assert td.days == 1
|
69 |
+
assert td._value == 86_400_000
|
70 |
+
assert td.components.days == 1
|
71 |
+
assert td._d == 1
|
72 |
+
assert td.total_seconds() == 86400
|
73 |
+
|
74 |
+
res = td.as_unit("us")
|
75 |
+
assert res._value == 86_400_000_000
|
76 |
+
assert res.components.days == 1
|
77 |
+
assert res.components.hours == 0
|
78 |
+
assert res._d == 1
|
79 |
+
assert res._h == 0
|
80 |
+
assert res.total_seconds() == 86400
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/methods/test_round.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from hypothesis import (
|
2 |
+
given,
|
3 |
+
strategies as st,
|
4 |
+
)
|
5 |
+
import numpy as np
|
6 |
+
import pytest
|
7 |
+
|
8 |
+
from pandas._libs import lib
|
9 |
+
from pandas._libs.tslibs import iNaT
|
10 |
+
from pandas.errors import OutOfBoundsTimedelta
|
11 |
+
|
12 |
+
from pandas import Timedelta
|
13 |
+
|
14 |
+
|
15 |
+
class TestTimedeltaRound:
|
16 |
+
@pytest.mark.parametrize(
|
17 |
+
"freq,s1,s2",
|
18 |
+
[
|
19 |
+
# This first case has s1, s2 being the same as t1,t2 below
|
20 |
+
(
|
21 |
+
"ns",
|
22 |
+
Timedelta("1 days 02:34:56.789123456"),
|
23 |
+
Timedelta("-1 days 02:34:56.789123456"),
|
24 |
+
),
|
25 |
+
(
|
26 |
+
"us",
|
27 |
+
Timedelta("1 days 02:34:56.789123000"),
|
28 |
+
Timedelta("-1 days 02:34:56.789123000"),
|
29 |
+
),
|
30 |
+
(
|
31 |
+
"ms",
|
32 |
+
Timedelta("1 days 02:34:56.789000000"),
|
33 |
+
Timedelta("-1 days 02:34:56.789000000"),
|
34 |
+
),
|
35 |
+
("s", Timedelta("1 days 02:34:57"), Timedelta("-1 days 02:34:57")),
|
36 |
+
("2s", Timedelta("1 days 02:34:56"), Timedelta("-1 days 02:34:56")),
|
37 |
+
("5s", Timedelta("1 days 02:34:55"), Timedelta("-1 days 02:34:55")),
|
38 |
+
("min", Timedelta("1 days 02:35:00"), Timedelta("-1 days 02:35:00")),
|
39 |
+
("12min", Timedelta("1 days 02:36:00"), Timedelta("-1 days 02:36:00")),
|
40 |
+
("h", Timedelta("1 days 03:00:00"), Timedelta("-1 days 03:00:00")),
|
41 |
+
("d", Timedelta("1 days"), Timedelta("-1 days")),
|
42 |
+
],
|
43 |
+
)
|
44 |
+
def test_round(self, freq, s1, s2):
|
45 |
+
t1 = Timedelta("1 days 02:34:56.789123456")
|
46 |
+
t2 = Timedelta("-1 days 02:34:56.789123456")
|
47 |
+
|
48 |
+
r1 = t1.round(freq)
|
49 |
+
assert r1 == s1
|
50 |
+
r2 = t2.round(freq)
|
51 |
+
assert r2 == s2
|
52 |
+
|
53 |
+
def test_round_invalid(self):
|
54 |
+
t1 = Timedelta("1 days 02:34:56.789123456")
|
55 |
+
|
56 |
+
for freq, msg in [
|
57 |
+
("YE", "<YearEnd: month=12> is a non-fixed frequency"),
|
58 |
+
("ME", "<MonthEnd> is a non-fixed frequency"),
|
59 |
+
("foobar", "Invalid frequency: foobar"),
|
60 |
+
]:
|
61 |
+
with pytest.raises(ValueError, match=msg):
|
62 |
+
t1.round(freq)
|
63 |
+
|
64 |
+
@pytest.mark.skip_ubsan
|
65 |
+
def test_round_implementation_bounds(self):
|
66 |
+
# See also: analogous test for Timestamp
|
67 |
+
# GH#38964
|
68 |
+
result = Timedelta.min.ceil("s")
|
69 |
+
expected = Timedelta.min + Timedelta(seconds=1) - Timedelta(145224193)
|
70 |
+
assert result == expected
|
71 |
+
|
72 |
+
result = Timedelta.max.floor("s")
|
73 |
+
expected = Timedelta.max - Timedelta(854775807)
|
74 |
+
assert result == expected
|
75 |
+
|
76 |
+
msg = (
|
77 |
+
r"Cannot round -106752 days \+00:12:43.145224193 to freq=s without overflow"
|
78 |
+
)
|
79 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
80 |
+
Timedelta.min.floor("s")
|
81 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
82 |
+
Timedelta.min.round("s")
|
83 |
+
|
84 |
+
msg = "Cannot round 106751 days 23:47:16.854775807 to freq=s without overflow"
|
85 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
86 |
+
Timedelta.max.ceil("s")
|
87 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
88 |
+
Timedelta.max.round("s")
|
89 |
+
|
90 |
+
@pytest.mark.skip_ubsan
|
91 |
+
@given(val=st.integers(min_value=iNaT + 1, max_value=lib.i8max))
|
92 |
+
@pytest.mark.parametrize(
|
93 |
+
"method", [Timedelta.round, Timedelta.floor, Timedelta.ceil]
|
94 |
+
)
|
95 |
+
def test_round_sanity(self, val, method):
|
96 |
+
cls = Timedelta
|
97 |
+
err_cls = OutOfBoundsTimedelta
|
98 |
+
|
99 |
+
val = np.int64(val)
|
100 |
+
td = cls(val)
|
101 |
+
|
102 |
+
def checker(ts, nanos, unit):
|
103 |
+
# First check that we do raise in cases where we should
|
104 |
+
if nanos == 1:
|
105 |
+
pass
|
106 |
+
else:
|
107 |
+
div, mod = divmod(ts._value, nanos)
|
108 |
+
diff = int(nanos - mod)
|
109 |
+
lb = ts._value - mod
|
110 |
+
assert lb <= ts._value # i.e. no overflows with python ints
|
111 |
+
ub = ts._value + diff
|
112 |
+
assert ub > ts._value # i.e. no overflows with python ints
|
113 |
+
|
114 |
+
msg = "without overflow"
|
115 |
+
if mod == 0:
|
116 |
+
# We should never be raising in this
|
117 |
+
pass
|
118 |
+
elif method is cls.ceil:
|
119 |
+
if ub > cls.max._value:
|
120 |
+
with pytest.raises(err_cls, match=msg):
|
121 |
+
method(ts, unit)
|
122 |
+
return
|
123 |
+
elif method is cls.floor:
|
124 |
+
if lb < cls.min._value:
|
125 |
+
with pytest.raises(err_cls, match=msg):
|
126 |
+
method(ts, unit)
|
127 |
+
return
|
128 |
+
elif mod >= diff:
|
129 |
+
if ub > cls.max._value:
|
130 |
+
with pytest.raises(err_cls, match=msg):
|
131 |
+
method(ts, unit)
|
132 |
+
return
|
133 |
+
elif lb < cls.min._value:
|
134 |
+
with pytest.raises(err_cls, match=msg):
|
135 |
+
method(ts, unit)
|
136 |
+
return
|
137 |
+
|
138 |
+
res = method(ts, unit)
|
139 |
+
|
140 |
+
td = res - ts
|
141 |
+
diff = abs(td._value)
|
142 |
+
assert diff < nanos
|
143 |
+
assert res._value % nanos == 0
|
144 |
+
|
145 |
+
if method is cls.round:
|
146 |
+
assert diff <= nanos / 2
|
147 |
+
elif method is cls.floor:
|
148 |
+
assert res <= ts
|
149 |
+
elif method is cls.ceil:
|
150 |
+
assert res >= ts
|
151 |
+
|
152 |
+
nanos = 1
|
153 |
+
checker(td, nanos, "ns")
|
154 |
+
|
155 |
+
nanos = 1000
|
156 |
+
checker(td, nanos, "us")
|
157 |
+
|
158 |
+
nanos = 1_000_000
|
159 |
+
checker(td, nanos, "ms")
|
160 |
+
|
161 |
+
nanos = 1_000_000_000
|
162 |
+
checker(td, nanos, "s")
|
163 |
+
|
164 |
+
nanos = 60 * 1_000_000_000
|
165 |
+
checker(td, nanos, "min")
|
166 |
+
|
167 |
+
nanos = 60 * 60 * 1_000_000_000
|
168 |
+
checker(td, nanos, "h")
|
169 |
+
|
170 |
+
nanos = 24 * 60 * 60 * 1_000_000_000
|
171 |
+
checker(td, nanos, "D")
|
172 |
+
|
173 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
174 |
+
def test_round_non_nano(self, unit):
|
175 |
+
td = Timedelta("1 days 02:34:57").as_unit(unit)
|
176 |
+
|
177 |
+
res = td.round("min")
|
178 |
+
assert res == Timedelta("1 days 02:35:00")
|
179 |
+
assert res._creso == td._creso
|
180 |
+
|
181 |
+
res = td.floor("min")
|
182 |
+
assert res == Timedelta("1 days 02:34:00")
|
183 |
+
assert res._creso == td._creso
|
184 |
+
|
185 |
+
res = td.ceil("min")
|
186 |
+
assert res == Timedelta("1 days 02:35:00")
|
187 |
+
assert res._creso == td._creso
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_arithmetic.py
ADDED
@@ -0,0 +1,1182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Tests for scalar Timedelta arithmetic ops
|
3 |
+
"""
|
4 |
+
from datetime import (
|
5 |
+
datetime,
|
6 |
+
timedelta,
|
7 |
+
)
|
8 |
+
import operator
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
import pytest
|
12 |
+
|
13 |
+
from pandas.errors import OutOfBoundsTimedelta
|
14 |
+
|
15 |
+
import pandas as pd
|
16 |
+
from pandas import (
|
17 |
+
NaT,
|
18 |
+
Timedelta,
|
19 |
+
Timestamp,
|
20 |
+
offsets,
|
21 |
+
)
|
22 |
+
import pandas._testing as tm
|
23 |
+
from pandas.core import ops
|
24 |
+
|
25 |
+
|
26 |
+
class TestTimedeltaAdditionSubtraction:
|
27 |
+
"""
|
28 |
+
Tests for Timedelta methods:
|
29 |
+
|
30 |
+
__add__, __radd__,
|
31 |
+
__sub__, __rsub__
|
32 |
+
"""
|
33 |
+
|
34 |
+
@pytest.mark.parametrize(
|
35 |
+
"ten_seconds",
|
36 |
+
[
|
37 |
+
Timedelta(10, unit="s"),
|
38 |
+
timedelta(seconds=10),
|
39 |
+
np.timedelta64(10, "s"),
|
40 |
+
np.timedelta64(10000000000, "ns"),
|
41 |
+
offsets.Second(10),
|
42 |
+
],
|
43 |
+
)
|
44 |
+
def test_td_add_sub_ten_seconds(self, ten_seconds):
|
45 |
+
# GH#6808
|
46 |
+
base = Timestamp("20130101 09:01:12.123456")
|
47 |
+
expected_add = Timestamp("20130101 09:01:22.123456")
|
48 |
+
expected_sub = Timestamp("20130101 09:01:02.123456")
|
49 |
+
|
50 |
+
result = base + ten_seconds
|
51 |
+
assert result == expected_add
|
52 |
+
|
53 |
+
result = base - ten_seconds
|
54 |
+
assert result == expected_sub
|
55 |
+
|
56 |
+
@pytest.mark.parametrize(
|
57 |
+
"one_day_ten_secs",
|
58 |
+
[
|
59 |
+
Timedelta("1 day, 00:00:10"),
|
60 |
+
Timedelta("1 days, 00:00:10"),
|
61 |
+
timedelta(days=1, seconds=10),
|
62 |
+
np.timedelta64(1, "D") + np.timedelta64(10, "s"),
|
63 |
+
offsets.Day() + offsets.Second(10),
|
64 |
+
],
|
65 |
+
)
|
66 |
+
def test_td_add_sub_one_day_ten_seconds(self, one_day_ten_secs):
|
67 |
+
# GH#6808
|
68 |
+
base = Timestamp("20130102 09:01:12.123456")
|
69 |
+
expected_add = Timestamp("20130103 09:01:22.123456")
|
70 |
+
expected_sub = Timestamp("20130101 09:01:02.123456")
|
71 |
+
|
72 |
+
result = base + one_day_ten_secs
|
73 |
+
assert result == expected_add
|
74 |
+
|
75 |
+
result = base - one_day_ten_secs
|
76 |
+
assert result == expected_sub
|
77 |
+
|
78 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
79 |
+
def test_td_add_datetimelike_scalar(self, op):
|
80 |
+
# GH#19738
|
81 |
+
td = Timedelta(10, unit="d")
|
82 |
+
|
83 |
+
result = op(td, datetime(2016, 1, 1))
|
84 |
+
if op is operator.add:
|
85 |
+
# datetime + Timedelta does _not_ call Timedelta.__radd__,
|
86 |
+
# so we get a datetime back instead of a Timestamp
|
87 |
+
assert isinstance(result, Timestamp)
|
88 |
+
assert result == Timestamp(2016, 1, 11)
|
89 |
+
|
90 |
+
result = op(td, Timestamp("2018-01-12 18:09"))
|
91 |
+
assert isinstance(result, Timestamp)
|
92 |
+
assert result == Timestamp("2018-01-22 18:09")
|
93 |
+
|
94 |
+
result = op(td, np.datetime64("2018-01-12"))
|
95 |
+
assert isinstance(result, Timestamp)
|
96 |
+
assert result == Timestamp("2018-01-22")
|
97 |
+
|
98 |
+
result = op(td, NaT)
|
99 |
+
assert result is NaT
|
100 |
+
|
101 |
+
def test_td_add_timestamp_overflow(self):
|
102 |
+
ts = Timestamp("1700-01-01").as_unit("ns")
|
103 |
+
msg = "Cannot cast 259987 from D to 'ns' without overflow."
|
104 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
105 |
+
ts + Timedelta(13 * 19999, unit="D")
|
106 |
+
|
107 |
+
msg = "Cannot cast 259987 days 00:00:00 to unit='ns' without overflow"
|
108 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
109 |
+
ts + timedelta(days=13 * 19999)
|
110 |
+
|
111 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
112 |
+
def test_td_add_td(self, op):
|
113 |
+
td = Timedelta(10, unit="d")
|
114 |
+
|
115 |
+
result = op(td, Timedelta(days=10))
|
116 |
+
assert isinstance(result, Timedelta)
|
117 |
+
assert result == Timedelta(days=20)
|
118 |
+
|
119 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
120 |
+
def test_td_add_pytimedelta(self, op):
|
121 |
+
td = Timedelta(10, unit="d")
|
122 |
+
result = op(td, timedelta(days=9))
|
123 |
+
assert isinstance(result, Timedelta)
|
124 |
+
assert result == Timedelta(days=19)
|
125 |
+
|
126 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
127 |
+
def test_td_add_timedelta64(self, op):
|
128 |
+
td = Timedelta(10, unit="d")
|
129 |
+
result = op(td, np.timedelta64(-4, "D"))
|
130 |
+
assert isinstance(result, Timedelta)
|
131 |
+
assert result == Timedelta(days=6)
|
132 |
+
|
133 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
134 |
+
def test_td_add_offset(self, op):
|
135 |
+
td = Timedelta(10, unit="d")
|
136 |
+
|
137 |
+
result = op(td, offsets.Hour(6))
|
138 |
+
assert isinstance(result, Timedelta)
|
139 |
+
assert result == Timedelta(days=10, hours=6)
|
140 |
+
|
141 |
+
def test_td_sub_td(self):
|
142 |
+
td = Timedelta(10, unit="d")
|
143 |
+
expected = Timedelta(0, unit="ns")
|
144 |
+
result = td - td
|
145 |
+
assert isinstance(result, Timedelta)
|
146 |
+
assert result == expected
|
147 |
+
|
148 |
+
def test_td_sub_pytimedelta(self):
|
149 |
+
td = Timedelta(10, unit="d")
|
150 |
+
expected = Timedelta(0, unit="ns")
|
151 |
+
|
152 |
+
result = td - td.to_pytimedelta()
|
153 |
+
assert isinstance(result, Timedelta)
|
154 |
+
assert result == expected
|
155 |
+
|
156 |
+
result = td.to_pytimedelta() - td
|
157 |
+
assert isinstance(result, Timedelta)
|
158 |
+
assert result == expected
|
159 |
+
|
160 |
+
def test_td_sub_timedelta64(self):
|
161 |
+
td = Timedelta(10, unit="d")
|
162 |
+
expected = Timedelta(0, unit="ns")
|
163 |
+
|
164 |
+
result = td - td.to_timedelta64()
|
165 |
+
assert isinstance(result, Timedelta)
|
166 |
+
assert result == expected
|
167 |
+
|
168 |
+
result = td.to_timedelta64() - td
|
169 |
+
assert isinstance(result, Timedelta)
|
170 |
+
assert result == expected
|
171 |
+
|
172 |
+
def test_td_sub_nat(self):
|
173 |
+
# In this context pd.NaT is treated as timedelta-like
|
174 |
+
td = Timedelta(10, unit="d")
|
175 |
+
result = td - NaT
|
176 |
+
assert result is NaT
|
177 |
+
|
178 |
+
def test_td_sub_td64_nat(self):
|
179 |
+
td = Timedelta(10, unit="d")
|
180 |
+
td_nat = np.timedelta64("NaT")
|
181 |
+
|
182 |
+
result = td - td_nat
|
183 |
+
assert result is NaT
|
184 |
+
|
185 |
+
result = td_nat - td
|
186 |
+
assert result is NaT
|
187 |
+
|
188 |
+
def test_td_sub_offset(self):
|
189 |
+
td = Timedelta(10, unit="d")
|
190 |
+
result = td - offsets.Hour(1)
|
191 |
+
assert isinstance(result, Timedelta)
|
192 |
+
assert result == Timedelta(239, unit="h")
|
193 |
+
|
194 |
+
def test_td_add_sub_numeric_raises(self):
|
195 |
+
td = Timedelta(10, unit="d")
|
196 |
+
msg = "unsupported operand type"
|
197 |
+
for other in [2, 2.0, np.int64(2), np.float64(2)]:
|
198 |
+
with pytest.raises(TypeError, match=msg):
|
199 |
+
td + other
|
200 |
+
with pytest.raises(TypeError, match=msg):
|
201 |
+
other + td
|
202 |
+
with pytest.raises(TypeError, match=msg):
|
203 |
+
td - other
|
204 |
+
with pytest.raises(TypeError, match=msg):
|
205 |
+
other - td
|
206 |
+
|
207 |
+
def test_td_add_sub_int_ndarray(self):
|
208 |
+
td = Timedelta("1 day")
|
209 |
+
other = np.array([1])
|
210 |
+
|
211 |
+
msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'"
|
212 |
+
with pytest.raises(TypeError, match=msg):
|
213 |
+
td + np.array([1])
|
214 |
+
|
215 |
+
msg = "|".join(
|
216 |
+
[
|
217 |
+
(
|
218 |
+
r"unsupported operand type\(s\) for \+: 'numpy.ndarray' "
|
219 |
+
"and 'Timedelta'"
|
220 |
+
),
|
221 |
+
# This message goes on to say "Please do not rely on this error;
|
222 |
+
# it may not be given on all Python implementations"
|
223 |
+
"Concatenation operation is not implemented for NumPy arrays",
|
224 |
+
]
|
225 |
+
)
|
226 |
+
with pytest.raises(TypeError, match=msg):
|
227 |
+
other + td
|
228 |
+
msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'"
|
229 |
+
with pytest.raises(TypeError, match=msg):
|
230 |
+
td - other
|
231 |
+
msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timedelta'"
|
232 |
+
with pytest.raises(TypeError, match=msg):
|
233 |
+
other - td
|
234 |
+
|
235 |
+
def test_td_rsub_nat(self):
|
236 |
+
td = Timedelta(10, unit="d")
|
237 |
+
result = NaT - td
|
238 |
+
assert result is NaT
|
239 |
+
|
240 |
+
result = np.datetime64("NaT") - td
|
241 |
+
assert result is NaT
|
242 |
+
|
243 |
+
def test_td_rsub_offset(self):
|
244 |
+
result = offsets.Hour(1) - Timedelta(10, unit="d")
|
245 |
+
assert isinstance(result, Timedelta)
|
246 |
+
assert result == Timedelta(-239, unit="h")
|
247 |
+
|
248 |
+
def test_td_sub_timedeltalike_object_dtype_array(self):
|
249 |
+
# GH#21980
|
250 |
+
arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")])
|
251 |
+
exp = np.array([Timestamp("20121231 9:01"), Timestamp("20121229 9:02")])
|
252 |
+
res = arr - Timedelta("1D")
|
253 |
+
tm.assert_numpy_array_equal(res, exp)
|
254 |
+
|
255 |
+
def test_td_sub_mixed_most_timedeltalike_object_dtype_array(self):
|
256 |
+
# GH#21980
|
257 |
+
now = Timestamp("2021-11-09 09:54:00")
|
258 |
+
arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")])
|
259 |
+
exp = np.array(
|
260 |
+
[
|
261 |
+
now - Timedelta("1D"),
|
262 |
+
Timedelta("0D"),
|
263 |
+
np.timedelta64(2, "h") - Timedelta("1D"),
|
264 |
+
]
|
265 |
+
)
|
266 |
+
res = arr - Timedelta("1D")
|
267 |
+
tm.assert_numpy_array_equal(res, exp)
|
268 |
+
|
269 |
+
def test_td_rsub_mixed_most_timedeltalike_object_dtype_array(self):
|
270 |
+
# GH#21980
|
271 |
+
now = Timestamp("2021-11-09 09:54:00")
|
272 |
+
arr = np.array([now, Timedelta("1D"), np.timedelta64(2, "h")])
|
273 |
+
msg = r"unsupported operand type\(s\) for \-: 'Timedelta' and 'Timestamp'"
|
274 |
+
with pytest.raises(TypeError, match=msg):
|
275 |
+
Timedelta("1D") - arr
|
276 |
+
|
277 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
278 |
+
def test_td_add_timedeltalike_object_dtype_array(self, op):
|
279 |
+
# GH#21980
|
280 |
+
arr = np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")])
|
281 |
+
exp = np.array([Timestamp("20130102 9:01"), Timestamp("20121231 9:02")])
|
282 |
+
res = op(arr, Timedelta("1D"))
|
283 |
+
tm.assert_numpy_array_equal(res, exp)
|
284 |
+
|
285 |
+
@pytest.mark.parametrize("op", [operator.add, ops.radd])
|
286 |
+
def test_td_add_mixed_timedeltalike_object_dtype_array(self, op):
|
287 |
+
# GH#21980
|
288 |
+
now = Timestamp("2021-11-09 09:54:00")
|
289 |
+
arr = np.array([now, Timedelta("1D")])
|
290 |
+
exp = np.array([now + Timedelta("1D"), Timedelta("2D")])
|
291 |
+
res = op(arr, Timedelta("1D"))
|
292 |
+
tm.assert_numpy_array_equal(res, exp)
|
293 |
+
|
294 |
+
def test_td_add_sub_td64_ndarray(self):
|
295 |
+
td = Timedelta("1 day")
|
296 |
+
|
297 |
+
other = np.array([td.to_timedelta64()])
|
298 |
+
expected = np.array([Timedelta("2 Days").to_timedelta64()])
|
299 |
+
|
300 |
+
result = td + other
|
301 |
+
tm.assert_numpy_array_equal(result, expected)
|
302 |
+
result = other + td
|
303 |
+
tm.assert_numpy_array_equal(result, expected)
|
304 |
+
|
305 |
+
result = td - other
|
306 |
+
tm.assert_numpy_array_equal(result, expected * 0)
|
307 |
+
result = other - td
|
308 |
+
tm.assert_numpy_array_equal(result, expected * 0)
|
309 |
+
|
310 |
+
def test_td_add_sub_dt64_ndarray(self):
|
311 |
+
td = Timedelta("1 day")
|
312 |
+
other = np.array(["2000-01-01"], dtype="M8[ns]")
|
313 |
+
|
314 |
+
expected = np.array(["2000-01-02"], dtype="M8[ns]")
|
315 |
+
tm.assert_numpy_array_equal(td + other, expected)
|
316 |
+
tm.assert_numpy_array_equal(other + td, expected)
|
317 |
+
|
318 |
+
expected = np.array(["1999-12-31"], dtype="M8[ns]")
|
319 |
+
tm.assert_numpy_array_equal(-td + other, expected)
|
320 |
+
tm.assert_numpy_array_equal(other - td, expected)
|
321 |
+
|
322 |
+
def test_td_add_sub_ndarray_0d(self):
|
323 |
+
td = Timedelta("1 day")
|
324 |
+
other = np.array(td.asm8)
|
325 |
+
|
326 |
+
result = td + other
|
327 |
+
assert isinstance(result, Timedelta)
|
328 |
+
assert result == 2 * td
|
329 |
+
|
330 |
+
result = other + td
|
331 |
+
assert isinstance(result, Timedelta)
|
332 |
+
assert result == 2 * td
|
333 |
+
|
334 |
+
result = other - td
|
335 |
+
assert isinstance(result, Timedelta)
|
336 |
+
assert result == 0 * td
|
337 |
+
|
338 |
+
result = td - other
|
339 |
+
assert isinstance(result, Timedelta)
|
340 |
+
assert result == 0 * td
|
341 |
+
|
342 |
+
|
343 |
+
class TestTimedeltaMultiplicationDivision:
|
344 |
+
"""
|
345 |
+
Tests for Timedelta methods:
|
346 |
+
|
347 |
+
__mul__, __rmul__,
|
348 |
+
__div__, __rdiv__,
|
349 |
+
__truediv__, __rtruediv__,
|
350 |
+
__floordiv__, __rfloordiv__,
|
351 |
+
__mod__, __rmod__,
|
352 |
+
__divmod__, __rdivmod__
|
353 |
+
"""
|
354 |
+
|
355 |
+
# ---------------------------------------------------------------
|
356 |
+
# Timedelta.__mul__, __rmul__
|
357 |
+
|
358 |
+
@pytest.mark.parametrize(
|
359 |
+
"td_nat", [NaT, np.timedelta64("NaT", "ns"), np.timedelta64("NaT")]
|
360 |
+
)
|
361 |
+
@pytest.mark.parametrize("op", [operator.mul, ops.rmul])
|
362 |
+
def test_td_mul_nat(self, op, td_nat):
|
363 |
+
# GH#19819
|
364 |
+
td = Timedelta(10, unit="d")
|
365 |
+
typs = "|".join(["numpy.timedelta64", "NaTType", "Timedelta"])
|
366 |
+
msg = "|".join(
|
367 |
+
[
|
368 |
+
rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'",
|
369 |
+
r"ufunc '?multiply'? cannot use operands with types",
|
370 |
+
]
|
371 |
+
)
|
372 |
+
with pytest.raises(TypeError, match=msg):
|
373 |
+
op(td, td_nat)
|
374 |
+
|
375 |
+
@pytest.mark.parametrize("nan", [np.nan, np.float64("NaN"), float("nan")])
|
376 |
+
@pytest.mark.parametrize("op", [operator.mul, ops.rmul])
|
377 |
+
def test_td_mul_nan(self, op, nan):
|
378 |
+
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
|
379 |
+
td = Timedelta(10, unit="d")
|
380 |
+
result = op(td, nan)
|
381 |
+
assert result is NaT
|
382 |
+
|
383 |
+
@pytest.mark.parametrize("op", [operator.mul, ops.rmul])
|
384 |
+
def test_td_mul_scalar(self, op):
|
385 |
+
# GH#19738
|
386 |
+
td = Timedelta(minutes=3)
|
387 |
+
|
388 |
+
result = op(td, 2)
|
389 |
+
assert result == Timedelta(minutes=6)
|
390 |
+
|
391 |
+
result = op(td, 1.5)
|
392 |
+
assert result == Timedelta(minutes=4, seconds=30)
|
393 |
+
|
394 |
+
assert op(td, np.nan) is NaT
|
395 |
+
|
396 |
+
assert op(-1, td)._value == -1 * td._value
|
397 |
+
assert op(-1.0, td)._value == -1.0 * td._value
|
398 |
+
|
399 |
+
msg = "unsupported operand type"
|
400 |
+
with pytest.raises(TypeError, match=msg):
|
401 |
+
# timedelta * datetime is gibberish
|
402 |
+
op(td, Timestamp(2016, 1, 2))
|
403 |
+
|
404 |
+
with pytest.raises(TypeError, match=msg):
|
405 |
+
# invalid multiply with another timedelta
|
406 |
+
op(td, td)
|
407 |
+
|
408 |
+
def test_td_mul_numeric_ndarray(self):
|
409 |
+
td = Timedelta("1 day")
|
410 |
+
other = np.array([2])
|
411 |
+
expected = np.array([Timedelta("2 Days").to_timedelta64()])
|
412 |
+
|
413 |
+
result = td * other
|
414 |
+
tm.assert_numpy_array_equal(result, expected)
|
415 |
+
|
416 |
+
result = other * td
|
417 |
+
tm.assert_numpy_array_equal(result, expected)
|
418 |
+
|
419 |
+
def test_td_mul_numeric_ndarray_0d(self):
|
420 |
+
td = Timedelta("1 day")
|
421 |
+
other = np.array(2)
|
422 |
+
assert other.ndim == 0
|
423 |
+
expected = Timedelta("2 days")
|
424 |
+
|
425 |
+
res = td * other
|
426 |
+
assert type(res) is Timedelta
|
427 |
+
assert res == expected
|
428 |
+
|
429 |
+
res = other * td
|
430 |
+
assert type(res) is Timedelta
|
431 |
+
assert res == expected
|
432 |
+
|
433 |
+
def test_td_mul_td64_ndarray_invalid(self):
|
434 |
+
td = Timedelta("1 day")
|
435 |
+
other = np.array([Timedelta("2 Days").to_timedelta64()])
|
436 |
+
|
437 |
+
msg = (
|
438 |
+
"ufunc '?multiply'? cannot use operands with types "
|
439 |
+
rf"dtype\('{tm.ENDIAN}m8\[ns\]'\) and dtype\('{tm.ENDIAN}m8\[ns\]'\)"
|
440 |
+
)
|
441 |
+
with pytest.raises(TypeError, match=msg):
|
442 |
+
td * other
|
443 |
+
with pytest.raises(TypeError, match=msg):
|
444 |
+
other * td
|
445 |
+
|
446 |
+
# ---------------------------------------------------------------
|
447 |
+
# Timedelta.__div__, __truediv__
|
448 |
+
|
449 |
+
def test_td_div_timedeltalike_scalar(self):
|
450 |
+
# GH#19738
|
451 |
+
td = Timedelta(10, unit="d")
|
452 |
+
|
453 |
+
result = td / offsets.Hour(1)
|
454 |
+
assert result == 240
|
455 |
+
|
456 |
+
assert td / td == 1
|
457 |
+
assert td / np.timedelta64(60, "h") == 4
|
458 |
+
|
459 |
+
assert np.isnan(td / NaT)
|
460 |
+
|
461 |
+
def test_td_div_td64_non_nano(self):
|
462 |
+
# truediv
|
463 |
+
td = Timedelta("1 days 2 hours 3 ns")
|
464 |
+
result = td / np.timedelta64(1, "D")
|
465 |
+
assert result == td._value / (86400 * 10**9)
|
466 |
+
result = td / np.timedelta64(1, "s")
|
467 |
+
assert result == td._value / 10**9
|
468 |
+
result = td / np.timedelta64(1, "ns")
|
469 |
+
assert result == td._value
|
470 |
+
|
471 |
+
# floordiv
|
472 |
+
td = Timedelta("1 days 2 hours 3 ns")
|
473 |
+
result = td // np.timedelta64(1, "D")
|
474 |
+
assert result == 1
|
475 |
+
result = td // np.timedelta64(1, "s")
|
476 |
+
assert result == 93600
|
477 |
+
result = td // np.timedelta64(1, "ns")
|
478 |
+
assert result == td._value
|
479 |
+
|
480 |
+
def test_td_div_numeric_scalar(self):
|
481 |
+
# GH#19738
|
482 |
+
td = Timedelta(10, unit="d")
|
483 |
+
|
484 |
+
result = td / 2
|
485 |
+
assert isinstance(result, Timedelta)
|
486 |
+
assert result == Timedelta(days=5)
|
487 |
+
|
488 |
+
result = td / 5
|
489 |
+
assert isinstance(result, Timedelta)
|
490 |
+
assert result == Timedelta(days=2)
|
491 |
+
|
492 |
+
@pytest.mark.parametrize(
|
493 |
+
"nan",
|
494 |
+
[
|
495 |
+
np.nan,
|
496 |
+
np.float64("NaN"),
|
497 |
+
float("nan"),
|
498 |
+
],
|
499 |
+
)
|
500 |
+
def test_td_div_nan(self, nan):
|
501 |
+
# np.float64('NaN') has a 'dtype' attr, avoid treating as array
|
502 |
+
td = Timedelta(10, unit="d")
|
503 |
+
result = td / nan
|
504 |
+
assert result is NaT
|
505 |
+
|
506 |
+
result = td // nan
|
507 |
+
assert result is NaT
|
508 |
+
|
509 |
+
def test_td_div_td64_ndarray(self):
|
510 |
+
td = Timedelta("1 day")
|
511 |
+
|
512 |
+
other = np.array([Timedelta("2 Days").to_timedelta64()])
|
513 |
+
expected = np.array([0.5])
|
514 |
+
|
515 |
+
result = td / other
|
516 |
+
tm.assert_numpy_array_equal(result, expected)
|
517 |
+
|
518 |
+
result = other / td
|
519 |
+
tm.assert_numpy_array_equal(result, expected * 4)
|
520 |
+
|
521 |
+
def test_td_div_ndarray_0d(self):
|
522 |
+
td = Timedelta("1 day")
|
523 |
+
|
524 |
+
other = np.array(1)
|
525 |
+
res = td / other
|
526 |
+
assert isinstance(res, Timedelta)
|
527 |
+
assert res == td
|
528 |
+
|
529 |
+
# ---------------------------------------------------------------
|
530 |
+
# Timedelta.__rdiv__
|
531 |
+
|
532 |
+
def test_td_rdiv_timedeltalike_scalar(self):
|
533 |
+
# GH#19738
|
534 |
+
td = Timedelta(10, unit="d")
|
535 |
+
result = offsets.Hour(1) / td
|
536 |
+
assert result == 1 / 240.0
|
537 |
+
|
538 |
+
assert np.timedelta64(60, "h") / td == 0.25
|
539 |
+
|
540 |
+
def test_td_rdiv_na_scalar(self):
|
541 |
+
# GH#31869 None gets cast to NaT
|
542 |
+
td = Timedelta(10, unit="d")
|
543 |
+
|
544 |
+
result = NaT / td
|
545 |
+
assert np.isnan(result)
|
546 |
+
|
547 |
+
result = None / td
|
548 |
+
assert np.isnan(result)
|
549 |
+
|
550 |
+
result = np.timedelta64("NaT") / td
|
551 |
+
assert np.isnan(result)
|
552 |
+
|
553 |
+
msg = r"unsupported operand type\(s\) for /: 'numpy.datetime64' and 'Timedelta'"
|
554 |
+
with pytest.raises(TypeError, match=msg):
|
555 |
+
np.datetime64("NaT") / td
|
556 |
+
|
557 |
+
msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"
|
558 |
+
with pytest.raises(TypeError, match=msg):
|
559 |
+
np.nan / td
|
560 |
+
|
561 |
+
def test_td_rdiv_ndarray(self):
|
562 |
+
td = Timedelta(10, unit="d")
|
563 |
+
|
564 |
+
arr = np.array([td], dtype=object)
|
565 |
+
result = arr / td
|
566 |
+
expected = np.array([1], dtype=np.float64)
|
567 |
+
tm.assert_numpy_array_equal(result, expected)
|
568 |
+
|
569 |
+
arr = np.array([None])
|
570 |
+
result = arr / td
|
571 |
+
expected = np.array([np.nan])
|
572 |
+
tm.assert_numpy_array_equal(result, expected)
|
573 |
+
|
574 |
+
arr = np.array([np.nan], dtype=object)
|
575 |
+
msg = r"unsupported operand type\(s\) for /: 'float' and 'Timedelta'"
|
576 |
+
with pytest.raises(TypeError, match=msg):
|
577 |
+
arr / td
|
578 |
+
|
579 |
+
arr = np.array([np.nan], dtype=np.float64)
|
580 |
+
msg = "cannot use operands with types dtype"
|
581 |
+
with pytest.raises(TypeError, match=msg):
|
582 |
+
arr / td
|
583 |
+
|
584 |
+
def test_td_rdiv_ndarray_0d(self):
|
585 |
+
td = Timedelta(10, unit="d")
|
586 |
+
|
587 |
+
arr = np.array(td.asm8)
|
588 |
+
|
589 |
+
assert arr / td == 1
|
590 |
+
|
591 |
+
# ---------------------------------------------------------------
|
592 |
+
# Timedelta.__floordiv__
|
593 |
+
|
594 |
+
def test_td_floordiv_timedeltalike_scalar(self):
|
595 |
+
# GH#18846
|
596 |
+
td = Timedelta(hours=3, minutes=4)
|
597 |
+
scalar = Timedelta(hours=3, minutes=3)
|
598 |
+
|
599 |
+
assert td // scalar == 1
|
600 |
+
assert -td // scalar.to_pytimedelta() == -2
|
601 |
+
assert (2 * td) // scalar.to_timedelta64() == 2
|
602 |
+
|
603 |
+
def test_td_floordiv_null_scalar(self):
|
604 |
+
# GH#18846
|
605 |
+
td = Timedelta(hours=3, minutes=4)
|
606 |
+
|
607 |
+
assert td // np.nan is NaT
|
608 |
+
assert np.isnan(td // NaT)
|
609 |
+
assert np.isnan(td // np.timedelta64("NaT"))
|
610 |
+
|
611 |
+
def test_td_floordiv_offsets(self):
|
612 |
+
# GH#19738
|
613 |
+
td = Timedelta(hours=3, minutes=4)
|
614 |
+
assert td // offsets.Hour(1) == 3
|
615 |
+
assert td // offsets.Minute(2) == 92
|
616 |
+
|
617 |
+
def test_td_floordiv_invalid_scalar(self):
|
618 |
+
# GH#18846
|
619 |
+
td = Timedelta(hours=3, minutes=4)
|
620 |
+
|
621 |
+
msg = "|".join(
|
622 |
+
[
|
623 |
+
r"Invalid dtype datetime64\[D\] for __floordiv__",
|
624 |
+
"'dtype' is an invalid keyword argument for this function",
|
625 |
+
r"ufunc '?floor_divide'? cannot use operands with types",
|
626 |
+
]
|
627 |
+
)
|
628 |
+
with pytest.raises(TypeError, match=msg):
|
629 |
+
td // np.datetime64("2016-01-01", dtype="datetime64[us]")
|
630 |
+
|
631 |
+
def test_td_floordiv_numeric_scalar(self):
|
632 |
+
# GH#18846
|
633 |
+
td = Timedelta(hours=3, minutes=4)
|
634 |
+
|
635 |
+
expected = Timedelta(hours=1, minutes=32)
|
636 |
+
assert td // 2 == expected
|
637 |
+
assert td // 2.0 == expected
|
638 |
+
assert td // np.float64(2.0) == expected
|
639 |
+
assert td // np.int32(2.0) == expected
|
640 |
+
assert td // np.uint8(2.0) == expected
|
641 |
+
|
642 |
+
def test_td_floordiv_timedeltalike_array(self):
|
643 |
+
# GH#18846
|
644 |
+
td = Timedelta(hours=3, minutes=4)
|
645 |
+
scalar = Timedelta(hours=3, minutes=3)
|
646 |
+
|
647 |
+
# Array-like others
|
648 |
+
assert td // np.array(scalar.to_timedelta64()) == 1
|
649 |
+
|
650 |
+
res = (3 * td) // np.array([scalar.to_timedelta64()])
|
651 |
+
expected = np.array([3], dtype=np.int64)
|
652 |
+
tm.assert_numpy_array_equal(res, expected)
|
653 |
+
|
654 |
+
res = (10 * td) // np.array([scalar.to_timedelta64(), np.timedelta64("NaT")])
|
655 |
+
expected = np.array([10, np.nan])
|
656 |
+
tm.assert_numpy_array_equal(res, expected)
|
657 |
+
|
658 |
+
def test_td_floordiv_numeric_series(self):
|
659 |
+
# GH#18846
|
660 |
+
td = Timedelta(hours=3, minutes=4)
|
661 |
+
ser = pd.Series([1], dtype=np.int64)
|
662 |
+
res = td // ser
|
663 |
+
assert res.dtype.kind == "m"
|
664 |
+
|
665 |
+
# ---------------------------------------------------------------
|
666 |
+
# Timedelta.__rfloordiv__
|
667 |
+
|
668 |
+
def test_td_rfloordiv_timedeltalike_scalar(self):
|
669 |
+
# GH#18846
|
670 |
+
td = Timedelta(hours=3, minutes=3)
|
671 |
+
scalar = Timedelta(hours=3, minutes=4)
|
672 |
+
|
673 |
+
# scalar others
|
674 |
+
# x // Timedelta is defined only for timedelta-like x. int-like,
|
675 |
+
# float-like, and date-like, in particular, should all either
|
676 |
+
# a) raise TypeError directly or
|
677 |
+
# b) return NotImplemented, following which the reversed
|
678 |
+
# operation will raise TypeError.
|
679 |
+
assert td.__rfloordiv__(scalar) == 1
|
680 |
+
assert (-td).__rfloordiv__(scalar.to_pytimedelta()) == -2
|
681 |
+
assert (2 * td).__rfloordiv__(scalar.to_timedelta64()) == 0
|
682 |
+
|
683 |
+
def test_td_rfloordiv_null_scalar(self):
|
684 |
+
# GH#18846
|
685 |
+
td = Timedelta(hours=3, minutes=3)
|
686 |
+
|
687 |
+
assert np.isnan(td.__rfloordiv__(NaT))
|
688 |
+
assert np.isnan(td.__rfloordiv__(np.timedelta64("NaT")))
|
689 |
+
|
690 |
+
def test_td_rfloordiv_offsets(self):
|
691 |
+
# GH#19738
|
692 |
+
assert offsets.Hour(1) // Timedelta(minutes=25) == 2
|
693 |
+
|
694 |
+
def test_td_rfloordiv_invalid_scalar(self):
|
695 |
+
# GH#18846
|
696 |
+
td = Timedelta(hours=3, minutes=3)
|
697 |
+
|
698 |
+
dt64 = np.datetime64("2016-01-01", "us")
|
699 |
+
|
700 |
+
assert td.__rfloordiv__(dt64) is NotImplemented
|
701 |
+
|
702 |
+
msg = (
|
703 |
+
r"unsupported operand type\(s\) for //: 'numpy.datetime64' and 'Timedelta'"
|
704 |
+
)
|
705 |
+
with pytest.raises(TypeError, match=msg):
|
706 |
+
dt64 // td
|
707 |
+
|
708 |
+
def test_td_rfloordiv_numeric_scalar(self):
|
709 |
+
# GH#18846
|
710 |
+
td = Timedelta(hours=3, minutes=3)
|
711 |
+
|
712 |
+
assert td.__rfloordiv__(np.nan) is NotImplemented
|
713 |
+
assert td.__rfloordiv__(3.5) is NotImplemented
|
714 |
+
assert td.__rfloordiv__(2) is NotImplemented
|
715 |
+
assert td.__rfloordiv__(np.float64(2.0)) is NotImplemented
|
716 |
+
assert td.__rfloordiv__(np.uint8(9)) is NotImplemented
|
717 |
+
assert td.__rfloordiv__(np.int32(2.0)) is NotImplemented
|
718 |
+
|
719 |
+
msg = r"unsupported operand type\(s\) for //: '.*' and 'Timedelta"
|
720 |
+
with pytest.raises(TypeError, match=msg):
|
721 |
+
np.float64(2.0) // td
|
722 |
+
with pytest.raises(TypeError, match=msg):
|
723 |
+
np.uint8(9) // td
|
724 |
+
with pytest.raises(TypeError, match=msg):
|
725 |
+
# deprecated GH#19761, enforced GH#29797
|
726 |
+
np.int32(2.0) // td
|
727 |
+
|
728 |
+
def test_td_rfloordiv_timedeltalike_array(self):
|
729 |
+
# GH#18846
|
730 |
+
td = Timedelta(hours=3, minutes=3)
|
731 |
+
scalar = Timedelta(hours=3, minutes=4)
|
732 |
+
|
733 |
+
# Array-like others
|
734 |
+
assert td.__rfloordiv__(np.array(scalar.to_timedelta64())) == 1
|
735 |
+
|
736 |
+
res = td.__rfloordiv__(np.array([(3 * scalar).to_timedelta64()]))
|
737 |
+
expected = np.array([3], dtype=np.int64)
|
738 |
+
tm.assert_numpy_array_equal(res, expected)
|
739 |
+
|
740 |
+
arr = np.array([(10 * scalar).to_timedelta64(), np.timedelta64("NaT")])
|
741 |
+
res = td.__rfloordiv__(arr)
|
742 |
+
expected = np.array([10, np.nan])
|
743 |
+
tm.assert_numpy_array_equal(res, expected)
|
744 |
+
|
745 |
+
def test_td_rfloordiv_intarray(self):
|
746 |
+
# deprecated GH#19761, enforced GH#29797
|
747 |
+
ints = np.array([1349654400, 1349740800, 1349827200, 1349913600]) * 10**9
|
748 |
+
|
749 |
+
msg = "Invalid dtype"
|
750 |
+
with pytest.raises(TypeError, match=msg):
|
751 |
+
ints // Timedelta(1, unit="s")
|
752 |
+
|
753 |
+
def test_td_rfloordiv_numeric_series(self):
|
754 |
+
# GH#18846
|
755 |
+
td = Timedelta(hours=3, minutes=3)
|
756 |
+
ser = pd.Series([1], dtype=np.int64)
|
757 |
+
res = td.__rfloordiv__(ser)
|
758 |
+
assert res is NotImplemented
|
759 |
+
|
760 |
+
msg = "Invalid dtype"
|
761 |
+
with pytest.raises(TypeError, match=msg):
|
762 |
+
# Deprecated GH#19761, enforced GH#29797
|
763 |
+
ser // td
|
764 |
+
|
765 |
+
# ----------------------------------------------------------------
|
766 |
+
# Timedelta.__mod__, __rmod__
|
767 |
+
|
768 |
+
def test_mod_timedeltalike(self):
|
769 |
+
# GH#19365
|
770 |
+
td = Timedelta(hours=37)
|
771 |
+
|
772 |
+
# Timedelta-like others
|
773 |
+
result = td % Timedelta(hours=6)
|
774 |
+
assert isinstance(result, Timedelta)
|
775 |
+
assert result == Timedelta(hours=1)
|
776 |
+
|
777 |
+
result = td % timedelta(minutes=60)
|
778 |
+
assert isinstance(result, Timedelta)
|
779 |
+
assert result == Timedelta(0)
|
780 |
+
|
781 |
+
result = td % NaT
|
782 |
+
assert result is NaT
|
783 |
+
|
784 |
+
def test_mod_timedelta64_nat(self):
|
785 |
+
# GH#19365
|
786 |
+
td = Timedelta(hours=37)
|
787 |
+
|
788 |
+
result = td % np.timedelta64("NaT", "ns")
|
789 |
+
assert result is NaT
|
790 |
+
|
791 |
+
def test_mod_timedelta64(self):
|
792 |
+
# GH#19365
|
793 |
+
td = Timedelta(hours=37)
|
794 |
+
|
795 |
+
result = td % np.timedelta64(2, "h")
|
796 |
+
assert isinstance(result, Timedelta)
|
797 |
+
assert result == Timedelta(hours=1)
|
798 |
+
|
799 |
+
def test_mod_offset(self):
|
800 |
+
# GH#19365
|
801 |
+
td = Timedelta(hours=37)
|
802 |
+
|
803 |
+
result = td % offsets.Hour(5)
|
804 |
+
assert isinstance(result, Timedelta)
|
805 |
+
assert result == Timedelta(hours=2)
|
806 |
+
|
807 |
+
def test_mod_numeric(self):
|
808 |
+
# GH#19365
|
809 |
+
td = Timedelta(hours=37)
|
810 |
+
|
811 |
+
# Numeric Others
|
812 |
+
result = td % 2
|
813 |
+
assert isinstance(result, Timedelta)
|
814 |
+
assert result == Timedelta(0)
|
815 |
+
|
816 |
+
result = td % 1e12
|
817 |
+
assert isinstance(result, Timedelta)
|
818 |
+
assert result == Timedelta(minutes=3, seconds=20)
|
819 |
+
|
820 |
+
result = td % int(1e12)
|
821 |
+
assert isinstance(result, Timedelta)
|
822 |
+
assert result == Timedelta(minutes=3, seconds=20)
|
823 |
+
|
824 |
+
def test_mod_invalid(self):
|
825 |
+
# GH#19365
|
826 |
+
td = Timedelta(hours=37)
|
827 |
+
msg = "unsupported operand type"
|
828 |
+
with pytest.raises(TypeError, match=msg):
|
829 |
+
td % Timestamp("2018-01-22")
|
830 |
+
|
831 |
+
with pytest.raises(TypeError, match=msg):
|
832 |
+
td % []
|
833 |
+
|
834 |
+
def test_rmod_pytimedelta(self):
|
835 |
+
# GH#19365
|
836 |
+
td = Timedelta(minutes=3)
|
837 |
+
|
838 |
+
result = timedelta(minutes=4) % td
|
839 |
+
assert isinstance(result, Timedelta)
|
840 |
+
assert result == Timedelta(minutes=1)
|
841 |
+
|
842 |
+
def test_rmod_timedelta64(self):
|
843 |
+
# GH#19365
|
844 |
+
td = Timedelta(minutes=3)
|
845 |
+
result = np.timedelta64(5, "m") % td
|
846 |
+
assert isinstance(result, Timedelta)
|
847 |
+
assert result == Timedelta(minutes=2)
|
848 |
+
|
849 |
+
def test_rmod_invalid(self):
|
850 |
+
# GH#19365
|
851 |
+
td = Timedelta(minutes=3)
|
852 |
+
|
853 |
+
msg = "unsupported operand"
|
854 |
+
with pytest.raises(TypeError, match=msg):
|
855 |
+
Timestamp("2018-01-22") % td
|
856 |
+
|
857 |
+
with pytest.raises(TypeError, match=msg):
|
858 |
+
15 % td
|
859 |
+
|
860 |
+
with pytest.raises(TypeError, match=msg):
|
861 |
+
16.0 % td
|
862 |
+
|
863 |
+
msg = "Invalid dtype int"
|
864 |
+
with pytest.raises(TypeError, match=msg):
|
865 |
+
np.array([22, 24]) % td
|
866 |
+
|
867 |
+
# ----------------------------------------------------------------
|
868 |
+
# Timedelta.__divmod__, __rdivmod__
|
869 |
+
|
870 |
+
def test_divmod_numeric(self):
|
871 |
+
# GH#19365
|
872 |
+
td = Timedelta(days=2, hours=6)
|
873 |
+
|
874 |
+
result = divmod(td, 53 * 3600 * 1e9)
|
875 |
+
assert result[0] == Timedelta(1, unit="ns")
|
876 |
+
assert isinstance(result[1], Timedelta)
|
877 |
+
assert result[1] == Timedelta(hours=1)
|
878 |
+
|
879 |
+
assert result
|
880 |
+
result = divmod(td, np.nan)
|
881 |
+
assert result[0] is NaT
|
882 |
+
assert result[1] is NaT
|
883 |
+
|
884 |
+
def test_divmod(self):
|
885 |
+
# GH#19365
|
886 |
+
td = Timedelta(days=2, hours=6)
|
887 |
+
|
888 |
+
result = divmod(td, timedelta(days=1))
|
889 |
+
assert result[0] == 2
|
890 |
+
assert isinstance(result[1], Timedelta)
|
891 |
+
assert result[1] == Timedelta(hours=6)
|
892 |
+
|
893 |
+
result = divmod(td, 54)
|
894 |
+
assert result[0] == Timedelta(hours=1)
|
895 |
+
assert isinstance(result[1], Timedelta)
|
896 |
+
assert result[1] == Timedelta(0)
|
897 |
+
|
898 |
+
result = divmod(td, NaT)
|
899 |
+
assert np.isnan(result[0])
|
900 |
+
assert result[1] is NaT
|
901 |
+
|
902 |
+
def test_divmod_offset(self):
|
903 |
+
# GH#19365
|
904 |
+
td = Timedelta(days=2, hours=6)
|
905 |
+
|
906 |
+
result = divmod(td, offsets.Hour(-4))
|
907 |
+
assert result[0] == -14
|
908 |
+
assert isinstance(result[1], Timedelta)
|
909 |
+
assert result[1] == Timedelta(hours=-2)
|
910 |
+
|
911 |
+
def test_divmod_invalid(self):
|
912 |
+
# GH#19365
|
913 |
+
td = Timedelta(days=2, hours=6)
|
914 |
+
|
915 |
+
msg = r"unsupported operand type\(s\) for //: 'Timedelta' and 'Timestamp'"
|
916 |
+
with pytest.raises(TypeError, match=msg):
|
917 |
+
divmod(td, Timestamp("2018-01-22"))
|
918 |
+
|
919 |
+
def test_rdivmod_pytimedelta(self):
|
920 |
+
# GH#19365
|
921 |
+
result = divmod(timedelta(days=2, hours=6), Timedelta(days=1))
|
922 |
+
assert result[0] == 2
|
923 |
+
assert isinstance(result[1], Timedelta)
|
924 |
+
assert result[1] == Timedelta(hours=6)
|
925 |
+
|
926 |
+
def test_rdivmod_offset(self):
|
927 |
+
result = divmod(offsets.Hour(54), Timedelta(hours=-4))
|
928 |
+
assert result[0] == -14
|
929 |
+
assert isinstance(result[1], Timedelta)
|
930 |
+
assert result[1] == Timedelta(hours=-2)
|
931 |
+
|
932 |
+
def test_rdivmod_invalid(self):
|
933 |
+
# GH#19365
|
934 |
+
td = Timedelta(minutes=3)
|
935 |
+
msg = "unsupported operand type"
|
936 |
+
|
937 |
+
with pytest.raises(TypeError, match=msg):
|
938 |
+
divmod(Timestamp("2018-01-22"), td)
|
939 |
+
|
940 |
+
with pytest.raises(TypeError, match=msg):
|
941 |
+
divmod(15, td)
|
942 |
+
|
943 |
+
with pytest.raises(TypeError, match=msg):
|
944 |
+
divmod(16.0, td)
|
945 |
+
|
946 |
+
msg = "Invalid dtype int"
|
947 |
+
with pytest.raises(TypeError, match=msg):
|
948 |
+
divmod(np.array([22, 24]), td)
|
949 |
+
|
950 |
+
# ----------------------------------------------------------------
|
951 |
+
|
952 |
+
@pytest.mark.parametrize(
|
953 |
+
"op", [operator.mul, ops.rmul, operator.truediv, ops.rdiv, ops.rsub]
|
954 |
+
)
|
955 |
+
@pytest.mark.parametrize(
|
956 |
+
"arr",
|
957 |
+
[
|
958 |
+
np.array([Timestamp("20130101 9:01"), Timestamp("20121230 9:02")]),
|
959 |
+
np.array([Timestamp("2021-11-09 09:54:00"), Timedelta("1D")]),
|
960 |
+
],
|
961 |
+
)
|
962 |
+
def test_td_op_timedelta_timedeltalike_array(self, op, arr):
|
963 |
+
msg = "unsupported operand type|cannot use operands with types"
|
964 |
+
with pytest.raises(TypeError, match=msg):
|
965 |
+
op(arr, Timedelta("1D"))
|
966 |
+
|
967 |
+
|
968 |
+
class TestTimedeltaComparison:
|
969 |
+
@pytest.mark.skip_ubsan
|
970 |
+
def test_compare_pytimedelta_bounds(self):
|
971 |
+
# GH#49021 don't overflow on comparison with very large pytimedeltas
|
972 |
+
|
973 |
+
for unit in ["ns", "us"]:
|
974 |
+
tdmax = Timedelta.max.as_unit(unit).max
|
975 |
+
tdmin = Timedelta.min.as_unit(unit).min
|
976 |
+
|
977 |
+
assert tdmax < timedelta.max
|
978 |
+
assert tdmax <= timedelta.max
|
979 |
+
assert not tdmax > timedelta.max
|
980 |
+
assert not tdmax >= timedelta.max
|
981 |
+
assert tdmax != timedelta.max
|
982 |
+
assert not tdmax == timedelta.max
|
983 |
+
|
984 |
+
assert tdmin > timedelta.min
|
985 |
+
assert tdmin >= timedelta.min
|
986 |
+
assert not tdmin < timedelta.min
|
987 |
+
assert not tdmin <= timedelta.min
|
988 |
+
assert tdmin != timedelta.min
|
989 |
+
assert not tdmin == timedelta.min
|
990 |
+
|
991 |
+
# But the "ms" and "s"-reso bounds extend pass pytimedelta
|
992 |
+
for unit in ["ms", "s"]:
|
993 |
+
tdmax = Timedelta.max.as_unit(unit).max
|
994 |
+
tdmin = Timedelta.min.as_unit(unit).min
|
995 |
+
|
996 |
+
assert tdmax > timedelta.max
|
997 |
+
assert tdmax >= timedelta.max
|
998 |
+
assert not tdmax < timedelta.max
|
999 |
+
assert not tdmax <= timedelta.max
|
1000 |
+
assert tdmax != timedelta.max
|
1001 |
+
assert not tdmax == timedelta.max
|
1002 |
+
|
1003 |
+
assert tdmin < timedelta.min
|
1004 |
+
assert tdmin <= timedelta.min
|
1005 |
+
assert not tdmin > timedelta.min
|
1006 |
+
assert not tdmin >= timedelta.min
|
1007 |
+
assert tdmin != timedelta.min
|
1008 |
+
assert not tdmin == timedelta.min
|
1009 |
+
|
1010 |
+
def test_compare_pytimedelta_bounds2(self):
|
1011 |
+
# a pytimedelta outside the microsecond bounds
|
1012 |
+
pytd = timedelta(days=999999999, seconds=86399)
|
1013 |
+
# NB: np.timedelta64(td, "s"") incorrectly overflows
|
1014 |
+
td64 = np.timedelta64(pytd.days, "D") + np.timedelta64(pytd.seconds, "s")
|
1015 |
+
td = Timedelta(td64)
|
1016 |
+
assert td.days == pytd.days
|
1017 |
+
assert td.seconds == pytd.seconds
|
1018 |
+
|
1019 |
+
assert td == pytd
|
1020 |
+
assert not td != pytd
|
1021 |
+
assert not td < pytd
|
1022 |
+
assert not td > pytd
|
1023 |
+
assert td <= pytd
|
1024 |
+
assert td >= pytd
|
1025 |
+
|
1026 |
+
td2 = td - Timedelta(seconds=1).as_unit("s")
|
1027 |
+
assert td2 != pytd
|
1028 |
+
assert not td2 == pytd
|
1029 |
+
assert td2 < pytd
|
1030 |
+
assert td2 <= pytd
|
1031 |
+
assert not td2 > pytd
|
1032 |
+
assert not td2 >= pytd
|
1033 |
+
|
1034 |
+
def test_compare_tick(self, tick_classes):
|
1035 |
+
cls = tick_classes
|
1036 |
+
|
1037 |
+
off = cls(4)
|
1038 |
+
td = off._as_pd_timedelta
|
1039 |
+
assert isinstance(td, Timedelta)
|
1040 |
+
|
1041 |
+
assert td == off
|
1042 |
+
assert not td != off
|
1043 |
+
assert td <= off
|
1044 |
+
assert td >= off
|
1045 |
+
assert not td < off
|
1046 |
+
assert not td > off
|
1047 |
+
|
1048 |
+
assert not td == 2 * off
|
1049 |
+
assert td != 2 * off
|
1050 |
+
assert td <= 2 * off
|
1051 |
+
assert td < 2 * off
|
1052 |
+
assert not td >= 2 * off
|
1053 |
+
assert not td > 2 * off
|
1054 |
+
|
1055 |
+
def test_comparison_object_array(self):
|
1056 |
+
# analogous to GH#15183
|
1057 |
+
td = Timedelta("2 days")
|
1058 |
+
other = Timedelta("3 hours")
|
1059 |
+
|
1060 |
+
arr = np.array([other, td], dtype=object)
|
1061 |
+
res = arr == td
|
1062 |
+
expected = np.array([False, True], dtype=bool)
|
1063 |
+
assert (res == expected).all()
|
1064 |
+
|
1065 |
+
# 2D case
|
1066 |
+
arr = np.array([[other, td], [td, other]], dtype=object)
|
1067 |
+
res = arr != td
|
1068 |
+
expected = np.array([[True, False], [False, True]], dtype=bool)
|
1069 |
+
assert res.shape == expected.shape
|
1070 |
+
assert (res == expected).all()
|
1071 |
+
|
1072 |
+
def test_compare_timedelta_ndarray(self):
|
1073 |
+
# GH#11835
|
1074 |
+
periods = [Timedelta("0 days 01:00:00"), Timedelta("0 days 01:00:00")]
|
1075 |
+
arr = np.array(periods)
|
1076 |
+
result = arr[0] > arr
|
1077 |
+
expected = np.array([False, False])
|
1078 |
+
tm.assert_numpy_array_equal(result, expected)
|
1079 |
+
|
1080 |
+
def test_compare_td64_ndarray(self):
|
1081 |
+
# GG#33441
|
1082 |
+
arr = np.arange(5).astype("timedelta64[ns]")
|
1083 |
+
td = Timedelta(arr[1])
|
1084 |
+
|
1085 |
+
expected = np.array([False, True, False, False, False], dtype=bool)
|
1086 |
+
|
1087 |
+
result = td == arr
|
1088 |
+
tm.assert_numpy_array_equal(result, expected)
|
1089 |
+
|
1090 |
+
result = arr == td
|
1091 |
+
tm.assert_numpy_array_equal(result, expected)
|
1092 |
+
|
1093 |
+
result = td != arr
|
1094 |
+
tm.assert_numpy_array_equal(result, ~expected)
|
1095 |
+
|
1096 |
+
result = arr != td
|
1097 |
+
tm.assert_numpy_array_equal(result, ~expected)
|
1098 |
+
|
1099 |
+
def test_compare_custom_object(self):
|
1100 |
+
"""
|
1101 |
+
Make sure non supported operations on Timedelta returns NonImplemented
|
1102 |
+
and yields to other operand (GH#20829).
|
1103 |
+
"""
|
1104 |
+
|
1105 |
+
class CustomClass:
|
1106 |
+
def __init__(self, cmp_result=None) -> None:
|
1107 |
+
self.cmp_result = cmp_result
|
1108 |
+
|
1109 |
+
def generic_result(self):
|
1110 |
+
if self.cmp_result is None:
|
1111 |
+
return NotImplemented
|
1112 |
+
else:
|
1113 |
+
return self.cmp_result
|
1114 |
+
|
1115 |
+
def __eq__(self, other):
|
1116 |
+
return self.generic_result()
|
1117 |
+
|
1118 |
+
def __gt__(self, other):
|
1119 |
+
return self.generic_result()
|
1120 |
+
|
1121 |
+
t = Timedelta("1s")
|
1122 |
+
|
1123 |
+
assert t != "string"
|
1124 |
+
assert t != 1
|
1125 |
+
assert t != CustomClass()
|
1126 |
+
assert t != CustomClass(cmp_result=False)
|
1127 |
+
|
1128 |
+
assert t < CustomClass(cmp_result=True)
|
1129 |
+
assert not t < CustomClass(cmp_result=False)
|
1130 |
+
|
1131 |
+
assert t == CustomClass(cmp_result=True)
|
1132 |
+
|
1133 |
+
@pytest.mark.parametrize("val", ["string", 1])
|
1134 |
+
def test_compare_unknown_type(self, val):
|
1135 |
+
# GH#20829
|
1136 |
+
t = Timedelta("1s")
|
1137 |
+
msg = "not supported between instances of 'Timedelta' and '(int|str)'"
|
1138 |
+
with pytest.raises(TypeError, match=msg):
|
1139 |
+
t >= val
|
1140 |
+
with pytest.raises(TypeError, match=msg):
|
1141 |
+
t > val
|
1142 |
+
with pytest.raises(TypeError, match=msg):
|
1143 |
+
t <= val
|
1144 |
+
with pytest.raises(TypeError, match=msg):
|
1145 |
+
t < val
|
1146 |
+
|
1147 |
+
|
1148 |
+
def test_ops_notimplemented():
|
1149 |
+
class Other:
|
1150 |
+
pass
|
1151 |
+
|
1152 |
+
other = Other()
|
1153 |
+
|
1154 |
+
td = Timedelta("1 day")
|
1155 |
+
assert td.__add__(other) is NotImplemented
|
1156 |
+
assert td.__sub__(other) is NotImplemented
|
1157 |
+
assert td.__truediv__(other) is NotImplemented
|
1158 |
+
assert td.__mul__(other) is NotImplemented
|
1159 |
+
assert td.__floordiv__(other) is NotImplemented
|
1160 |
+
|
1161 |
+
|
1162 |
+
def test_ops_error_str():
|
1163 |
+
# GH#13624
|
1164 |
+
td = Timedelta("1 day")
|
1165 |
+
|
1166 |
+
for left, right in [(td, "a"), ("a", td)]:
|
1167 |
+
msg = "|".join(
|
1168 |
+
[
|
1169 |
+
"unsupported operand type",
|
1170 |
+
r'can only concatenate str \(not "Timedelta"\) to str',
|
1171 |
+
"must be str, not Timedelta",
|
1172 |
+
]
|
1173 |
+
)
|
1174 |
+
with pytest.raises(TypeError, match=msg):
|
1175 |
+
left + right
|
1176 |
+
|
1177 |
+
msg = "not supported between instances of"
|
1178 |
+
with pytest.raises(TypeError, match=msg):
|
1179 |
+
left > right
|
1180 |
+
|
1181 |
+
assert not left == right # pylint: disable=unneeded-not
|
1182 |
+
assert left != right
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_constructors.py
ADDED
@@ -0,0 +1,698 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
from itertools import product
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
|
7 |
+
from pandas._libs.tslibs import OutOfBoundsTimedelta
|
8 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
9 |
+
|
10 |
+
from pandas import (
|
11 |
+
Index,
|
12 |
+
NaT,
|
13 |
+
Timedelta,
|
14 |
+
TimedeltaIndex,
|
15 |
+
offsets,
|
16 |
+
to_timedelta,
|
17 |
+
)
|
18 |
+
import pandas._testing as tm
|
19 |
+
|
20 |
+
|
21 |
+
class TestTimedeltaConstructorUnitKeyword:
|
22 |
+
@pytest.mark.parametrize("unit", ["Y", "y", "M"])
|
23 |
+
def test_unit_m_y_raises(self, unit):
|
24 |
+
msg = "Units 'M', 'Y', and 'y' are no longer supported"
|
25 |
+
|
26 |
+
with pytest.raises(ValueError, match=msg):
|
27 |
+
Timedelta(10, unit)
|
28 |
+
|
29 |
+
with pytest.raises(ValueError, match=msg):
|
30 |
+
to_timedelta(10, unit)
|
31 |
+
|
32 |
+
with pytest.raises(ValueError, match=msg):
|
33 |
+
to_timedelta([1, 2], unit)
|
34 |
+
|
35 |
+
@pytest.mark.parametrize(
|
36 |
+
"unit,unit_depr",
|
37 |
+
[
|
38 |
+
("h", "H"),
|
39 |
+
("min", "T"),
|
40 |
+
("s", "S"),
|
41 |
+
("ms", "L"),
|
42 |
+
("ns", "N"),
|
43 |
+
("us", "U"),
|
44 |
+
],
|
45 |
+
)
|
46 |
+
def test_units_H_T_S_L_N_U_deprecated(self, unit, unit_depr):
|
47 |
+
# GH#52536
|
48 |
+
msg = f"'{unit_depr}' is deprecated and will be removed in a future version."
|
49 |
+
|
50 |
+
expected = Timedelta(1, unit=unit)
|
51 |
+
with tm.assert_produces_warning(FutureWarning, match=msg):
|
52 |
+
result = Timedelta(1, unit=unit_depr)
|
53 |
+
tm.assert_equal(result, expected)
|
54 |
+
|
55 |
+
@pytest.mark.parametrize(
|
56 |
+
"unit, np_unit",
|
57 |
+
[(value, "W") for value in ["W", "w"]]
|
58 |
+
+ [(value, "D") for value in ["D", "d", "days", "day", "Days", "Day"]]
|
59 |
+
+ [
|
60 |
+
(value, "m")
|
61 |
+
for value in [
|
62 |
+
"m",
|
63 |
+
"minute",
|
64 |
+
"min",
|
65 |
+
"minutes",
|
66 |
+
"Minute",
|
67 |
+
"Min",
|
68 |
+
"Minutes",
|
69 |
+
]
|
70 |
+
]
|
71 |
+
+ [
|
72 |
+
(value, "s")
|
73 |
+
for value in [
|
74 |
+
"s",
|
75 |
+
"seconds",
|
76 |
+
"sec",
|
77 |
+
"second",
|
78 |
+
"Seconds",
|
79 |
+
"Sec",
|
80 |
+
"Second",
|
81 |
+
]
|
82 |
+
]
|
83 |
+
+ [
|
84 |
+
(value, "ms")
|
85 |
+
for value in [
|
86 |
+
"ms",
|
87 |
+
"milliseconds",
|
88 |
+
"millisecond",
|
89 |
+
"milli",
|
90 |
+
"millis",
|
91 |
+
"MS",
|
92 |
+
"Milliseconds",
|
93 |
+
"Millisecond",
|
94 |
+
"Milli",
|
95 |
+
"Millis",
|
96 |
+
]
|
97 |
+
]
|
98 |
+
+ [
|
99 |
+
(value, "us")
|
100 |
+
for value in [
|
101 |
+
"us",
|
102 |
+
"microseconds",
|
103 |
+
"microsecond",
|
104 |
+
"micro",
|
105 |
+
"micros",
|
106 |
+
"u",
|
107 |
+
"US",
|
108 |
+
"Microseconds",
|
109 |
+
"Microsecond",
|
110 |
+
"Micro",
|
111 |
+
"Micros",
|
112 |
+
"U",
|
113 |
+
]
|
114 |
+
]
|
115 |
+
+ [
|
116 |
+
(value, "ns")
|
117 |
+
for value in [
|
118 |
+
"ns",
|
119 |
+
"nanoseconds",
|
120 |
+
"nanosecond",
|
121 |
+
"nano",
|
122 |
+
"nanos",
|
123 |
+
"n",
|
124 |
+
"NS",
|
125 |
+
"Nanoseconds",
|
126 |
+
"Nanosecond",
|
127 |
+
"Nano",
|
128 |
+
"Nanos",
|
129 |
+
"N",
|
130 |
+
]
|
131 |
+
],
|
132 |
+
)
|
133 |
+
@pytest.mark.parametrize("wrapper", [np.array, list, Index])
|
134 |
+
def test_unit_parser(self, unit, np_unit, wrapper):
|
135 |
+
# validate all units, GH 6855, GH 21762
|
136 |
+
# array-likes
|
137 |
+
expected = TimedeltaIndex(
|
138 |
+
[np.timedelta64(i, np_unit) for i in np.arange(5).tolist()],
|
139 |
+
dtype="m8[ns]",
|
140 |
+
)
|
141 |
+
# TODO(2.0): the desired output dtype may have non-nano resolution
|
142 |
+
msg = f"'{unit}' is deprecated and will be removed in a future version."
|
143 |
+
|
144 |
+
if (unit, np_unit) in (("u", "us"), ("U", "us"), ("n", "ns"), ("N", "ns")):
|
145 |
+
warn = FutureWarning
|
146 |
+
else:
|
147 |
+
warn = FutureWarning
|
148 |
+
msg = "The 'unit' keyword in TimedeltaIndex construction is deprecated"
|
149 |
+
with tm.assert_produces_warning(warn, match=msg):
|
150 |
+
result = to_timedelta(wrapper(range(5)), unit=unit)
|
151 |
+
tm.assert_index_equal(result, expected)
|
152 |
+
result = TimedeltaIndex(wrapper(range(5)), unit=unit)
|
153 |
+
tm.assert_index_equal(result, expected)
|
154 |
+
|
155 |
+
str_repr = [f"{x}{unit}" for x in np.arange(5)]
|
156 |
+
result = to_timedelta(wrapper(str_repr))
|
157 |
+
tm.assert_index_equal(result, expected)
|
158 |
+
result = to_timedelta(wrapper(str_repr))
|
159 |
+
tm.assert_index_equal(result, expected)
|
160 |
+
|
161 |
+
# scalar
|
162 |
+
expected = Timedelta(np.timedelta64(2, np_unit).astype("timedelta64[ns]"))
|
163 |
+
result = to_timedelta(2, unit=unit)
|
164 |
+
assert result == expected
|
165 |
+
result = Timedelta(2, unit=unit)
|
166 |
+
assert result == expected
|
167 |
+
|
168 |
+
result = to_timedelta(f"2{unit}")
|
169 |
+
assert result == expected
|
170 |
+
result = Timedelta(f"2{unit}")
|
171 |
+
assert result == expected
|
172 |
+
|
173 |
+
|
174 |
+
def test_construct_from_kwargs_overflow():
|
175 |
+
# GH#55503
|
176 |
+
msg = "seconds=86400000000000000000, milliseconds=0, microseconds=0, nanoseconds=0"
|
177 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
178 |
+
Timedelta(days=10**6)
|
179 |
+
msg = "seconds=60000000000000000000, milliseconds=0, microseconds=0, nanoseconds=0"
|
180 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
181 |
+
Timedelta(minutes=10**9)
|
182 |
+
|
183 |
+
|
184 |
+
def test_construct_with_weeks_unit_overflow():
|
185 |
+
# GH#47268 don't silently wrap around
|
186 |
+
with pytest.raises(OutOfBoundsTimedelta, match="without overflow"):
|
187 |
+
Timedelta(1000000000000000000, unit="W")
|
188 |
+
|
189 |
+
with pytest.raises(OutOfBoundsTimedelta, match="without overflow"):
|
190 |
+
Timedelta(1000000000000000000.0, unit="W")
|
191 |
+
|
192 |
+
|
193 |
+
def test_construct_from_td64_with_unit():
|
194 |
+
# ignore the unit, as it may cause silently overflows leading to incorrect
|
195 |
+
# results, and in non-overflow cases is irrelevant GH#46827
|
196 |
+
obj = np.timedelta64(123456789000000000, "h")
|
197 |
+
|
198 |
+
with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):
|
199 |
+
Timedelta(obj, unit="ps")
|
200 |
+
|
201 |
+
with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):
|
202 |
+
Timedelta(obj, unit="ns")
|
203 |
+
|
204 |
+
with pytest.raises(OutOfBoundsTimedelta, match="123456789000000000 hours"):
|
205 |
+
Timedelta(obj)
|
206 |
+
|
207 |
+
|
208 |
+
def test_from_td64_retain_resolution():
|
209 |
+
# case where we retain millisecond resolution
|
210 |
+
obj = np.timedelta64(12345, "ms")
|
211 |
+
|
212 |
+
td = Timedelta(obj)
|
213 |
+
assert td._value == obj.view("i8")
|
214 |
+
assert td._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
215 |
+
|
216 |
+
# Case where we cast to nearest-supported reso
|
217 |
+
obj2 = np.timedelta64(1234, "D")
|
218 |
+
td2 = Timedelta(obj2)
|
219 |
+
assert td2._creso == NpyDatetimeUnit.NPY_FR_s.value
|
220 |
+
assert td2 == obj2
|
221 |
+
assert td2.days == 1234
|
222 |
+
|
223 |
+
# Case that _would_ overflow if we didn't support non-nano
|
224 |
+
obj3 = np.timedelta64(1000000000000000000, "us")
|
225 |
+
td3 = Timedelta(obj3)
|
226 |
+
assert td3.total_seconds() == 1000000000000
|
227 |
+
assert td3._creso == NpyDatetimeUnit.NPY_FR_us.value
|
228 |
+
|
229 |
+
|
230 |
+
def test_from_pytimedelta_us_reso():
|
231 |
+
# pytimedelta has microsecond resolution, so Timedelta(pytd) inherits that
|
232 |
+
td = timedelta(days=4, minutes=3)
|
233 |
+
result = Timedelta(td)
|
234 |
+
assert result.to_pytimedelta() == td
|
235 |
+
assert result._creso == NpyDatetimeUnit.NPY_FR_us.value
|
236 |
+
|
237 |
+
|
238 |
+
def test_from_tick_reso():
|
239 |
+
tick = offsets.Nano()
|
240 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_ns.value
|
241 |
+
|
242 |
+
tick = offsets.Micro()
|
243 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_us.value
|
244 |
+
|
245 |
+
tick = offsets.Milli()
|
246 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
247 |
+
|
248 |
+
tick = offsets.Second()
|
249 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value
|
250 |
+
|
251 |
+
# everything above Second gets cast to the closest supported reso: second
|
252 |
+
tick = offsets.Minute()
|
253 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value
|
254 |
+
|
255 |
+
tick = offsets.Hour()
|
256 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value
|
257 |
+
|
258 |
+
tick = offsets.Day()
|
259 |
+
assert Timedelta(tick)._creso == NpyDatetimeUnit.NPY_FR_s.value
|
260 |
+
|
261 |
+
|
262 |
+
def test_construction():
|
263 |
+
expected = np.timedelta64(10, "D").astype("m8[ns]").view("i8")
|
264 |
+
assert Timedelta(10, unit="d")._value == expected
|
265 |
+
assert Timedelta(10.0, unit="d")._value == expected
|
266 |
+
assert Timedelta("10 days")._value == expected
|
267 |
+
assert Timedelta(days=10)._value == expected
|
268 |
+
assert Timedelta(days=10.0)._value == expected
|
269 |
+
|
270 |
+
expected += np.timedelta64(10, "s").astype("m8[ns]").view("i8")
|
271 |
+
assert Timedelta("10 days 00:00:10")._value == expected
|
272 |
+
assert Timedelta(days=10, seconds=10)._value == expected
|
273 |
+
assert Timedelta(days=10, milliseconds=10 * 1000)._value == expected
|
274 |
+
assert Timedelta(days=10, microseconds=10 * 1000 * 1000)._value == expected
|
275 |
+
|
276 |
+
# rounding cases
|
277 |
+
assert Timedelta(82739999850000)._value == 82739999850000
|
278 |
+
assert "0 days 22:58:59.999850" in str(Timedelta(82739999850000))
|
279 |
+
assert Timedelta(123072001000000)._value == 123072001000000
|
280 |
+
assert "1 days 10:11:12.001" in str(Timedelta(123072001000000))
|
281 |
+
|
282 |
+
# string conversion with/without leading zero
|
283 |
+
# GH#9570
|
284 |
+
assert Timedelta("0:00:00") == timedelta(hours=0)
|
285 |
+
assert Timedelta("00:00:00") == timedelta(hours=0)
|
286 |
+
assert Timedelta("-1:00:00") == -timedelta(hours=1)
|
287 |
+
assert Timedelta("-01:00:00") == -timedelta(hours=1)
|
288 |
+
|
289 |
+
# more strings & abbrevs
|
290 |
+
# GH#8190
|
291 |
+
assert Timedelta("1 h") == timedelta(hours=1)
|
292 |
+
assert Timedelta("1 hour") == timedelta(hours=1)
|
293 |
+
assert Timedelta("1 hr") == timedelta(hours=1)
|
294 |
+
assert Timedelta("1 hours") == timedelta(hours=1)
|
295 |
+
assert Timedelta("-1 hours") == -timedelta(hours=1)
|
296 |
+
assert Timedelta("1 m") == timedelta(minutes=1)
|
297 |
+
assert Timedelta("1.5 m") == timedelta(seconds=90)
|
298 |
+
assert Timedelta("1 minute") == timedelta(minutes=1)
|
299 |
+
assert Timedelta("1 minutes") == timedelta(minutes=1)
|
300 |
+
assert Timedelta("1 s") == timedelta(seconds=1)
|
301 |
+
assert Timedelta("1 second") == timedelta(seconds=1)
|
302 |
+
assert Timedelta("1 seconds") == timedelta(seconds=1)
|
303 |
+
assert Timedelta("1 ms") == timedelta(milliseconds=1)
|
304 |
+
assert Timedelta("1 milli") == timedelta(milliseconds=1)
|
305 |
+
assert Timedelta("1 millisecond") == timedelta(milliseconds=1)
|
306 |
+
assert Timedelta("1 us") == timedelta(microseconds=1)
|
307 |
+
assert Timedelta("1 µs") == timedelta(microseconds=1)
|
308 |
+
assert Timedelta("1 micros") == timedelta(microseconds=1)
|
309 |
+
assert Timedelta("1 microsecond") == timedelta(microseconds=1)
|
310 |
+
assert Timedelta("1.5 microsecond") == Timedelta("00:00:00.000001500")
|
311 |
+
assert Timedelta("1 ns") == Timedelta("00:00:00.000000001")
|
312 |
+
assert Timedelta("1 nano") == Timedelta("00:00:00.000000001")
|
313 |
+
assert Timedelta("1 nanosecond") == Timedelta("00:00:00.000000001")
|
314 |
+
|
315 |
+
# combos
|
316 |
+
assert Timedelta("10 days 1 hour") == timedelta(days=10, hours=1)
|
317 |
+
assert Timedelta("10 days 1 h") == timedelta(days=10, hours=1)
|
318 |
+
assert Timedelta("10 days 1 h 1m 1s") == timedelta(
|
319 |
+
days=10, hours=1, minutes=1, seconds=1
|
320 |
+
)
|
321 |
+
assert Timedelta("-10 days 1 h 1m 1s") == -timedelta(
|
322 |
+
days=10, hours=1, minutes=1, seconds=1
|
323 |
+
)
|
324 |
+
assert Timedelta("-10 days 1 h 1m 1s") == -timedelta(
|
325 |
+
days=10, hours=1, minutes=1, seconds=1
|
326 |
+
)
|
327 |
+
assert Timedelta("-10 days 1 h 1m 1s 3us") == -timedelta(
|
328 |
+
days=10, hours=1, minutes=1, seconds=1, microseconds=3
|
329 |
+
)
|
330 |
+
assert Timedelta("-10 days 1 h 1.5m 1s 3us") == -timedelta(
|
331 |
+
days=10, hours=1, minutes=1, seconds=31, microseconds=3
|
332 |
+
)
|
333 |
+
|
334 |
+
# Currently invalid as it has a - on the hh:mm:dd part
|
335 |
+
# (only allowed on the days)
|
336 |
+
msg = "only leading negative signs are allowed"
|
337 |
+
with pytest.raises(ValueError, match=msg):
|
338 |
+
Timedelta("-10 days -1 h 1.5m 1s 3us")
|
339 |
+
|
340 |
+
# only leading neg signs are allowed
|
341 |
+
with pytest.raises(ValueError, match=msg):
|
342 |
+
Timedelta("10 days -1 h 1.5m 1s 3us")
|
343 |
+
|
344 |
+
# no units specified
|
345 |
+
msg = "no units specified"
|
346 |
+
with pytest.raises(ValueError, match=msg):
|
347 |
+
Timedelta("3.1415")
|
348 |
+
|
349 |
+
# invalid construction
|
350 |
+
msg = "cannot construct a Timedelta"
|
351 |
+
with pytest.raises(ValueError, match=msg):
|
352 |
+
Timedelta()
|
353 |
+
|
354 |
+
msg = "unit abbreviation w/o a number"
|
355 |
+
with pytest.raises(ValueError, match=msg):
|
356 |
+
Timedelta("foo")
|
357 |
+
|
358 |
+
msg = (
|
359 |
+
"cannot construct a Timedelta from "
|
360 |
+
"the passed arguments, allowed keywords are "
|
361 |
+
)
|
362 |
+
with pytest.raises(ValueError, match=msg):
|
363 |
+
Timedelta(day=10)
|
364 |
+
|
365 |
+
# floats
|
366 |
+
expected = np.timedelta64(10, "s").astype("m8[ns]").view("i8") + np.timedelta64(
|
367 |
+
500, "ms"
|
368 |
+
).astype("m8[ns]").view("i8")
|
369 |
+
assert Timedelta(10.5, unit="s")._value == expected
|
370 |
+
|
371 |
+
# offset
|
372 |
+
assert to_timedelta(offsets.Hour(2)) == Timedelta(hours=2)
|
373 |
+
assert Timedelta(offsets.Hour(2)) == Timedelta(hours=2)
|
374 |
+
assert Timedelta(offsets.Second(2)) == Timedelta(seconds=2)
|
375 |
+
|
376 |
+
# GH#11995: unicode
|
377 |
+
expected = Timedelta("1h")
|
378 |
+
result = Timedelta("1h")
|
379 |
+
assert result == expected
|
380 |
+
assert to_timedelta(offsets.Hour(2)) == Timedelta("0 days, 02:00:00")
|
381 |
+
|
382 |
+
msg = "unit abbreviation w/o a number"
|
383 |
+
with pytest.raises(ValueError, match=msg):
|
384 |
+
Timedelta("foo bar")
|
385 |
+
|
386 |
+
|
387 |
+
@pytest.mark.parametrize(
|
388 |
+
"item",
|
389 |
+
list(
|
390 |
+
{
|
391 |
+
"days": "D",
|
392 |
+
"seconds": "s",
|
393 |
+
"microseconds": "us",
|
394 |
+
"milliseconds": "ms",
|
395 |
+
"minutes": "m",
|
396 |
+
"hours": "h",
|
397 |
+
"weeks": "W",
|
398 |
+
}.items()
|
399 |
+
),
|
400 |
+
)
|
401 |
+
@pytest.mark.parametrize(
|
402 |
+
"npdtype", [np.int64, np.int32, np.int16, np.float64, np.float32, np.float16]
|
403 |
+
)
|
404 |
+
def test_td_construction_with_np_dtypes(npdtype, item):
|
405 |
+
# GH#8757: test construction with np dtypes
|
406 |
+
pykwarg, npkwarg = item
|
407 |
+
expected = np.timedelta64(1, npkwarg).astype("m8[ns]").view("i8")
|
408 |
+
assert Timedelta(**{pykwarg: npdtype(1)})._value == expected
|
409 |
+
|
410 |
+
|
411 |
+
@pytest.mark.parametrize(
|
412 |
+
"val",
|
413 |
+
[
|
414 |
+
"1s",
|
415 |
+
"-1s",
|
416 |
+
"1us",
|
417 |
+
"-1us",
|
418 |
+
"1 day",
|
419 |
+
"-1 day",
|
420 |
+
"-23:59:59.999999",
|
421 |
+
"-1 days +23:59:59.999999",
|
422 |
+
"-1ns",
|
423 |
+
"1ns",
|
424 |
+
"-23:59:59.999999999",
|
425 |
+
],
|
426 |
+
)
|
427 |
+
def test_td_from_repr_roundtrip(val):
|
428 |
+
# round-trip both for string and value
|
429 |
+
td = Timedelta(val)
|
430 |
+
assert Timedelta(td._value) == td
|
431 |
+
|
432 |
+
assert Timedelta(str(td)) == td
|
433 |
+
assert Timedelta(td._repr_base(format="all")) == td
|
434 |
+
assert Timedelta(td._repr_base()) == td
|
435 |
+
|
436 |
+
|
437 |
+
def test_overflow_on_construction():
|
438 |
+
# GH#3374
|
439 |
+
value = Timedelta("1day")._value * 20169940
|
440 |
+
msg = "Cannot cast 1742682816000000000000 from ns to 'ns' without overflow"
|
441 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
442 |
+
Timedelta(value)
|
443 |
+
|
444 |
+
# xref GH#17637
|
445 |
+
msg = "Cannot cast 139993 from D to 'ns' without overflow"
|
446 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
447 |
+
Timedelta(7 * 19999, unit="D")
|
448 |
+
|
449 |
+
# used to overflow before non-ns support
|
450 |
+
td = Timedelta(timedelta(days=13 * 19999))
|
451 |
+
assert td._creso == NpyDatetimeUnit.NPY_FR_us.value
|
452 |
+
assert td.days == 13 * 19999
|
453 |
+
|
454 |
+
|
455 |
+
@pytest.mark.parametrize(
|
456 |
+
"val, unit",
|
457 |
+
[
|
458 |
+
(15251, "W"), # 1
|
459 |
+
(106752, "D"), # change from previous:
|
460 |
+
(2562048, "h"), # 0 hours
|
461 |
+
(153722868, "m"), # 13 minutes
|
462 |
+
(9223372037, "s"), # 44 seconds
|
463 |
+
],
|
464 |
+
)
|
465 |
+
def test_construction_out_of_bounds_td64ns(val, unit):
|
466 |
+
# TODO: parametrize over units just above/below the implementation bounds
|
467 |
+
# once GH#38964 is resolved
|
468 |
+
|
469 |
+
# Timedelta.max is just under 106752 days
|
470 |
+
td64 = np.timedelta64(val, unit)
|
471 |
+
assert td64.astype("m8[ns]").view("i8") < 0 # i.e. naive astype will be wrong
|
472 |
+
|
473 |
+
td = Timedelta(td64)
|
474 |
+
if unit != "M":
|
475 |
+
# with unit="M" the conversion to "s" is poorly defined
|
476 |
+
# (and numpy issues DeprecationWarning)
|
477 |
+
assert td.asm8 == td64
|
478 |
+
assert td.asm8.dtype == "m8[s]"
|
479 |
+
msg = r"Cannot cast 1067\d\d days .* to unit='ns' without overflow"
|
480 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
481 |
+
td.as_unit("ns")
|
482 |
+
|
483 |
+
# But just back in bounds and we are OK
|
484 |
+
assert Timedelta(td64 - 1) == td64 - 1
|
485 |
+
|
486 |
+
td64 *= -1
|
487 |
+
assert td64.astype("m8[ns]").view("i8") > 0 # i.e. naive astype will be wrong
|
488 |
+
|
489 |
+
td2 = Timedelta(td64)
|
490 |
+
msg = r"Cannot cast -1067\d\d days .* to unit='ns' without overflow"
|
491 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
492 |
+
td2.as_unit("ns")
|
493 |
+
|
494 |
+
# But just back in bounds and we are OK
|
495 |
+
assert Timedelta(td64 + 1) == td64 + 1
|
496 |
+
|
497 |
+
|
498 |
+
@pytest.mark.parametrize(
|
499 |
+
"val, unit",
|
500 |
+
[
|
501 |
+
(15251 * 10**9, "W"),
|
502 |
+
(106752 * 10**9, "D"),
|
503 |
+
(2562048 * 10**9, "h"),
|
504 |
+
(153722868 * 10**9, "m"),
|
505 |
+
],
|
506 |
+
)
|
507 |
+
def test_construction_out_of_bounds_td64s(val, unit):
|
508 |
+
td64 = np.timedelta64(val, unit)
|
509 |
+
with pytest.raises(OutOfBoundsTimedelta, match=str(td64)):
|
510 |
+
Timedelta(td64)
|
511 |
+
|
512 |
+
# But just back in bounds and we are OK
|
513 |
+
assert Timedelta(td64 - 10**9) == td64 - 10**9
|
514 |
+
|
515 |
+
|
516 |
+
@pytest.mark.parametrize(
|
517 |
+
"fmt,exp",
|
518 |
+
[
|
519 |
+
(
|
520 |
+
"P6DT0H50M3.010010012S",
|
521 |
+
Timedelta(
|
522 |
+
days=6,
|
523 |
+
minutes=50,
|
524 |
+
seconds=3,
|
525 |
+
milliseconds=10,
|
526 |
+
microseconds=10,
|
527 |
+
nanoseconds=12,
|
528 |
+
),
|
529 |
+
),
|
530 |
+
(
|
531 |
+
"P-6DT0H50M3.010010012S",
|
532 |
+
Timedelta(
|
533 |
+
days=-6,
|
534 |
+
minutes=50,
|
535 |
+
seconds=3,
|
536 |
+
milliseconds=10,
|
537 |
+
microseconds=10,
|
538 |
+
nanoseconds=12,
|
539 |
+
),
|
540 |
+
),
|
541 |
+
("P4DT12H30M5S", Timedelta(days=4, hours=12, minutes=30, seconds=5)),
|
542 |
+
("P0DT0H0M0.000000123S", Timedelta(nanoseconds=123)),
|
543 |
+
("P0DT0H0M0.00001S", Timedelta(microseconds=10)),
|
544 |
+
("P0DT0H0M0.001S", Timedelta(milliseconds=1)),
|
545 |
+
("P0DT0H1M0S", Timedelta(minutes=1)),
|
546 |
+
("P1DT25H61M61S", Timedelta(days=1, hours=25, minutes=61, seconds=61)),
|
547 |
+
("PT1S", Timedelta(seconds=1)),
|
548 |
+
("PT0S", Timedelta(seconds=0)),
|
549 |
+
("P1WT0S", Timedelta(days=7, seconds=0)),
|
550 |
+
("P1D", Timedelta(days=1)),
|
551 |
+
("P1DT1H", Timedelta(days=1, hours=1)),
|
552 |
+
("P1W", Timedelta(days=7)),
|
553 |
+
("PT300S", Timedelta(seconds=300)),
|
554 |
+
("P1DT0H0M00000000000S", Timedelta(days=1)),
|
555 |
+
("PT-6H3M", Timedelta(hours=-6, minutes=3)),
|
556 |
+
("-PT6H3M", Timedelta(hours=-6, minutes=-3)),
|
557 |
+
("-PT-6H+3M", Timedelta(hours=6, minutes=-3)),
|
558 |
+
],
|
559 |
+
)
|
560 |
+
def test_iso_constructor(fmt, exp):
|
561 |
+
assert Timedelta(fmt) == exp
|
562 |
+
|
563 |
+
|
564 |
+
@pytest.mark.parametrize(
|
565 |
+
"fmt",
|
566 |
+
[
|
567 |
+
"PPPPPPPPPPPP",
|
568 |
+
"PDTHMS",
|
569 |
+
"P0DT999H999M999S",
|
570 |
+
"P1DT0H0M0.0000000000000S",
|
571 |
+
"P1DT0H0M0.S",
|
572 |
+
"P",
|
573 |
+
"-P",
|
574 |
+
],
|
575 |
+
)
|
576 |
+
def test_iso_constructor_raises(fmt):
|
577 |
+
msg = f"Invalid ISO 8601 Duration format - {fmt}"
|
578 |
+
with pytest.raises(ValueError, match=msg):
|
579 |
+
Timedelta(fmt)
|
580 |
+
|
581 |
+
|
582 |
+
@pytest.mark.parametrize(
|
583 |
+
"constructed_td, conversion",
|
584 |
+
[
|
585 |
+
(Timedelta(nanoseconds=100), "100ns"),
|
586 |
+
(
|
587 |
+
Timedelta(
|
588 |
+
days=1,
|
589 |
+
hours=1,
|
590 |
+
minutes=1,
|
591 |
+
weeks=1,
|
592 |
+
seconds=1,
|
593 |
+
milliseconds=1,
|
594 |
+
microseconds=1,
|
595 |
+
nanoseconds=1,
|
596 |
+
),
|
597 |
+
694861001001001,
|
598 |
+
),
|
599 |
+
(Timedelta(microseconds=1) + Timedelta(nanoseconds=1), "1us1ns"),
|
600 |
+
(Timedelta(microseconds=1) - Timedelta(nanoseconds=1), "999ns"),
|
601 |
+
(Timedelta(microseconds=1) + 5 * Timedelta(nanoseconds=-2), "990ns"),
|
602 |
+
],
|
603 |
+
)
|
604 |
+
def test_td_constructor_on_nanoseconds(constructed_td, conversion):
|
605 |
+
# GH#9273
|
606 |
+
assert constructed_td == Timedelta(conversion)
|
607 |
+
|
608 |
+
|
609 |
+
def test_td_constructor_value_error():
|
610 |
+
msg = "Invalid type <class 'str'>. Must be int or float."
|
611 |
+
with pytest.raises(TypeError, match=msg):
|
612 |
+
Timedelta(nanoseconds="abc")
|
613 |
+
|
614 |
+
|
615 |
+
def test_timedelta_constructor_identity():
|
616 |
+
# Test for #30543
|
617 |
+
expected = Timedelta(np.timedelta64(1, "s"))
|
618 |
+
result = Timedelta(expected)
|
619 |
+
assert result is expected
|
620 |
+
|
621 |
+
|
622 |
+
def test_timedelta_pass_td_and_kwargs_raises():
|
623 |
+
# don't silently ignore the kwargs GH#48898
|
624 |
+
td = Timedelta(days=1)
|
625 |
+
msg = (
|
626 |
+
"Cannot pass both a Timedelta input and timedelta keyword arguments, "
|
627 |
+
r"got \['days'\]"
|
628 |
+
)
|
629 |
+
with pytest.raises(ValueError, match=msg):
|
630 |
+
Timedelta(td, days=2)
|
631 |
+
|
632 |
+
|
633 |
+
@pytest.mark.parametrize(
|
634 |
+
"constructor, value, unit, expectation",
|
635 |
+
[
|
636 |
+
(Timedelta, "10s", "ms", (ValueError, "unit must not be specified")),
|
637 |
+
(to_timedelta, "10s", "ms", (ValueError, "unit must not be specified")),
|
638 |
+
(to_timedelta, ["1", 2, 3], "s", (ValueError, "unit must not be specified")),
|
639 |
+
],
|
640 |
+
)
|
641 |
+
def test_string_with_unit(constructor, value, unit, expectation):
|
642 |
+
exp, match = expectation
|
643 |
+
with pytest.raises(exp, match=match):
|
644 |
+
_ = constructor(value, unit=unit)
|
645 |
+
|
646 |
+
|
647 |
+
@pytest.mark.parametrize(
|
648 |
+
"value",
|
649 |
+
[
|
650 |
+
"".join(elements)
|
651 |
+
for repetition in (1, 2)
|
652 |
+
for elements in product("+-, ", repeat=repetition)
|
653 |
+
],
|
654 |
+
)
|
655 |
+
def test_string_without_numbers(value):
|
656 |
+
# GH39710 Timedelta input string with only symbols and no digits raises an error
|
657 |
+
msg = (
|
658 |
+
"symbols w/o a number"
|
659 |
+
if value != "--"
|
660 |
+
else "only leading negative signs are allowed"
|
661 |
+
)
|
662 |
+
with pytest.raises(ValueError, match=msg):
|
663 |
+
Timedelta(value)
|
664 |
+
|
665 |
+
|
666 |
+
def test_timedelta_new_npnat():
|
667 |
+
# GH#48898
|
668 |
+
nat = np.timedelta64("NaT", "h")
|
669 |
+
assert Timedelta(nat) is NaT
|
670 |
+
|
671 |
+
|
672 |
+
def test_subclass_respected():
|
673 |
+
# GH#49579
|
674 |
+
class MyCustomTimedelta(Timedelta):
|
675 |
+
pass
|
676 |
+
|
677 |
+
td = MyCustomTimedelta("1 minute")
|
678 |
+
assert isinstance(td, MyCustomTimedelta)
|
679 |
+
|
680 |
+
|
681 |
+
def test_non_nano_value():
|
682 |
+
# https://github.com/pandas-dev/pandas/issues/49076
|
683 |
+
result = Timedelta(10, unit="D").as_unit("s").value
|
684 |
+
# `.value` shows nanoseconds, even though unit is 's'
|
685 |
+
assert result == 864000000000000
|
686 |
+
|
687 |
+
# out-of-nanoseconds-bounds `.value` raises informative message
|
688 |
+
msg = (
|
689 |
+
r"Cannot convert Timedelta to nanoseconds without overflow. "
|
690 |
+
r"Use `.asm8.view\('i8'\)` to cast represent Timedelta in its "
|
691 |
+
r"own unit \(here, s\).$"
|
692 |
+
)
|
693 |
+
td = Timedelta(1_000, "D").as_unit("s") * 1_000
|
694 |
+
with pytest.raises(OverflowError, match=msg):
|
695 |
+
td.value
|
696 |
+
# check that the suggested workaround actually works
|
697 |
+
result = td.asm8.view("i8")
|
698 |
+
assert result == 86400000000
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_formats.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas import Timedelta
|
4 |
+
|
5 |
+
|
6 |
+
@pytest.mark.parametrize(
|
7 |
+
"td, expected_repr",
|
8 |
+
[
|
9 |
+
(Timedelta(10, unit="d"), "Timedelta('10 days 00:00:00')"),
|
10 |
+
(Timedelta(10, unit="s"), "Timedelta('0 days 00:00:10')"),
|
11 |
+
(Timedelta(10, unit="ms"), "Timedelta('0 days 00:00:00.010000')"),
|
12 |
+
(Timedelta(-10, unit="ms"), "Timedelta('-1 days +23:59:59.990000')"),
|
13 |
+
],
|
14 |
+
)
|
15 |
+
def test_repr(td, expected_repr):
|
16 |
+
assert repr(td) == expected_repr
|
17 |
+
|
18 |
+
|
19 |
+
@pytest.mark.parametrize(
|
20 |
+
"td, expected_iso",
|
21 |
+
[
|
22 |
+
(
|
23 |
+
Timedelta(
|
24 |
+
days=6,
|
25 |
+
minutes=50,
|
26 |
+
seconds=3,
|
27 |
+
milliseconds=10,
|
28 |
+
microseconds=10,
|
29 |
+
nanoseconds=12,
|
30 |
+
),
|
31 |
+
"P6DT0H50M3.010010012S",
|
32 |
+
),
|
33 |
+
(Timedelta(days=4, hours=12, minutes=30, seconds=5), "P4DT12H30M5S"),
|
34 |
+
(Timedelta(nanoseconds=123), "P0DT0H0M0.000000123S"),
|
35 |
+
# trim nano
|
36 |
+
(Timedelta(microseconds=10), "P0DT0H0M0.00001S"),
|
37 |
+
# trim micro
|
38 |
+
(Timedelta(milliseconds=1), "P0DT0H0M0.001S"),
|
39 |
+
# don't strip every 0
|
40 |
+
(Timedelta(minutes=1), "P0DT0H1M0S"),
|
41 |
+
],
|
42 |
+
)
|
43 |
+
def test_isoformat(td, expected_iso):
|
44 |
+
assert td.isoformat() == expected_iso
|
45 |
+
|
46 |
+
|
47 |
+
class TestReprBase:
|
48 |
+
def test_none(self):
|
49 |
+
delta_1d = Timedelta(1, unit="D")
|
50 |
+
delta_0d = Timedelta(0, unit="D")
|
51 |
+
delta_1s = Timedelta(1, unit="s")
|
52 |
+
delta_500ms = Timedelta(500, unit="ms")
|
53 |
+
|
54 |
+
drepr = lambda x: x._repr_base()
|
55 |
+
assert drepr(delta_1d) == "1 days"
|
56 |
+
assert drepr(-delta_1d) == "-1 days"
|
57 |
+
assert drepr(delta_0d) == "0 days"
|
58 |
+
assert drepr(delta_1s) == "0 days 00:00:01"
|
59 |
+
assert drepr(delta_500ms) == "0 days 00:00:00.500000"
|
60 |
+
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
|
61 |
+
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
|
62 |
+
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
|
63 |
+
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
|
64 |
+
|
65 |
+
def test_sub_day(self):
|
66 |
+
delta_1d = Timedelta(1, unit="D")
|
67 |
+
delta_0d = Timedelta(0, unit="D")
|
68 |
+
delta_1s = Timedelta(1, unit="s")
|
69 |
+
delta_500ms = Timedelta(500, unit="ms")
|
70 |
+
|
71 |
+
drepr = lambda x: x._repr_base(format="sub_day")
|
72 |
+
assert drepr(delta_1d) == "1 days"
|
73 |
+
assert drepr(-delta_1d) == "-1 days"
|
74 |
+
assert drepr(delta_0d) == "00:00:00"
|
75 |
+
assert drepr(delta_1s) == "00:00:01"
|
76 |
+
assert drepr(delta_500ms) == "00:00:00.500000"
|
77 |
+
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
|
78 |
+
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
|
79 |
+
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
|
80 |
+
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
|
81 |
+
|
82 |
+
def test_long(self):
|
83 |
+
delta_1d = Timedelta(1, unit="D")
|
84 |
+
delta_0d = Timedelta(0, unit="D")
|
85 |
+
delta_1s = Timedelta(1, unit="s")
|
86 |
+
delta_500ms = Timedelta(500, unit="ms")
|
87 |
+
|
88 |
+
drepr = lambda x: x._repr_base(format="long")
|
89 |
+
assert drepr(delta_1d) == "1 days 00:00:00"
|
90 |
+
assert drepr(-delta_1d) == "-1 days +00:00:00"
|
91 |
+
assert drepr(delta_0d) == "0 days 00:00:00"
|
92 |
+
assert drepr(delta_1s) == "0 days 00:00:01"
|
93 |
+
assert drepr(delta_500ms) == "0 days 00:00:00.500000"
|
94 |
+
assert drepr(delta_1d + delta_1s) == "1 days 00:00:01"
|
95 |
+
assert drepr(-delta_1d + delta_1s) == "-1 days +00:00:01"
|
96 |
+
assert drepr(delta_1d + delta_500ms) == "1 days 00:00:00.500000"
|
97 |
+
assert drepr(-delta_1d + delta_500ms) == "-1 days +00:00:00.500000"
|
98 |
+
|
99 |
+
def test_all(self):
|
100 |
+
delta_1d = Timedelta(1, unit="D")
|
101 |
+
delta_0d = Timedelta(0, unit="D")
|
102 |
+
delta_1ns = Timedelta(1, unit="ns")
|
103 |
+
|
104 |
+
drepr = lambda x: x._repr_base(format="all")
|
105 |
+
assert drepr(delta_1d) == "1 days 00:00:00.000000000"
|
106 |
+
assert drepr(-delta_1d) == "-1 days +00:00:00.000000000"
|
107 |
+
assert drepr(delta_0d) == "0 days 00:00:00.000000000"
|
108 |
+
assert drepr(delta_1ns) == "0 days 00:00:00.000000001"
|
109 |
+
assert drepr(-delta_1d + delta_1ns) == "-1 days +00:00:00.000000001"
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_timedelta.py
ADDED
@@ -0,0 +1,666 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" test the scalar Timedelta """
|
2 |
+
from datetime import timedelta
|
3 |
+
import sys
|
4 |
+
|
5 |
+
from hypothesis import (
|
6 |
+
given,
|
7 |
+
strategies as st,
|
8 |
+
)
|
9 |
+
import numpy as np
|
10 |
+
import pytest
|
11 |
+
|
12 |
+
from pandas._libs import lib
|
13 |
+
from pandas._libs.tslibs import (
|
14 |
+
NaT,
|
15 |
+
iNaT,
|
16 |
+
)
|
17 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
18 |
+
from pandas.errors import OutOfBoundsTimedelta
|
19 |
+
|
20 |
+
from pandas import (
|
21 |
+
Timedelta,
|
22 |
+
to_timedelta,
|
23 |
+
)
|
24 |
+
import pandas._testing as tm
|
25 |
+
|
26 |
+
|
27 |
+
class TestNonNano:
|
28 |
+
@pytest.fixture(params=["s", "ms", "us"])
|
29 |
+
def unit_str(self, request):
|
30 |
+
return request.param
|
31 |
+
|
32 |
+
@pytest.fixture
|
33 |
+
def unit(self, unit_str):
|
34 |
+
# 7, 8, 9 correspond to second, millisecond, and microsecond, respectively
|
35 |
+
attr = f"NPY_FR_{unit_str}"
|
36 |
+
return getattr(NpyDatetimeUnit, attr).value
|
37 |
+
|
38 |
+
@pytest.fixture
|
39 |
+
def val(self, unit):
|
40 |
+
# microsecond that would be just out of bounds for nano
|
41 |
+
us = 9223372800000000
|
42 |
+
if unit == NpyDatetimeUnit.NPY_FR_us.value:
|
43 |
+
value = us
|
44 |
+
elif unit == NpyDatetimeUnit.NPY_FR_ms.value:
|
45 |
+
value = us // 1000
|
46 |
+
else:
|
47 |
+
value = us // 1_000_000
|
48 |
+
return value
|
49 |
+
|
50 |
+
@pytest.fixture
|
51 |
+
def td(self, unit, val):
|
52 |
+
return Timedelta._from_value_and_reso(val, unit)
|
53 |
+
|
54 |
+
def test_from_value_and_reso(self, unit, val):
|
55 |
+
# Just checking that the fixture is giving us what we asked for
|
56 |
+
td = Timedelta._from_value_and_reso(val, unit)
|
57 |
+
assert td._value == val
|
58 |
+
assert td._creso == unit
|
59 |
+
assert td.days == 106752
|
60 |
+
|
61 |
+
def test_unary_non_nano(self, td, unit):
|
62 |
+
assert abs(td)._creso == unit
|
63 |
+
assert (-td)._creso == unit
|
64 |
+
assert (+td)._creso == unit
|
65 |
+
|
66 |
+
def test_sub_preserves_reso(self, td, unit):
|
67 |
+
res = td - td
|
68 |
+
expected = Timedelta._from_value_and_reso(0, unit)
|
69 |
+
assert res == expected
|
70 |
+
assert res._creso == unit
|
71 |
+
|
72 |
+
def test_mul_preserves_reso(self, td, unit):
|
73 |
+
# The td fixture should always be far from the implementation
|
74 |
+
# bound, so doubling does not risk overflow.
|
75 |
+
res = td * 2
|
76 |
+
assert res._value == td._value * 2
|
77 |
+
assert res._creso == unit
|
78 |
+
|
79 |
+
def test_cmp_cross_reso(self, td):
|
80 |
+
# numpy gets this wrong because of silent overflow
|
81 |
+
other = Timedelta(days=106751, unit="ns")
|
82 |
+
assert other < td
|
83 |
+
assert td > other
|
84 |
+
assert not other == td
|
85 |
+
assert td != other
|
86 |
+
|
87 |
+
def test_to_pytimedelta(self, td):
|
88 |
+
res = td.to_pytimedelta()
|
89 |
+
expected = timedelta(days=106752)
|
90 |
+
assert type(res) is timedelta
|
91 |
+
assert res == expected
|
92 |
+
|
93 |
+
def test_to_timedelta64(self, td, unit):
|
94 |
+
for res in [td.to_timedelta64(), td.to_numpy(), td.asm8]:
|
95 |
+
assert isinstance(res, np.timedelta64)
|
96 |
+
assert res.view("i8") == td._value
|
97 |
+
if unit == NpyDatetimeUnit.NPY_FR_s.value:
|
98 |
+
assert res.dtype == "m8[s]"
|
99 |
+
elif unit == NpyDatetimeUnit.NPY_FR_ms.value:
|
100 |
+
assert res.dtype == "m8[ms]"
|
101 |
+
elif unit == NpyDatetimeUnit.NPY_FR_us.value:
|
102 |
+
assert res.dtype == "m8[us]"
|
103 |
+
|
104 |
+
def test_truediv_timedeltalike(self, td):
|
105 |
+
assert td / td == 1
|
106 |
+
assert (2.5 * td) / td == 2.5
|
107 |
+
|
108 |
+
other = Timedelta(td._value)
|
109 |
+
msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow."
|
110 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
111 |
+
td / other
|
112 |
+
|
113 |
+
# Timedelta(other.to_pytimedelta()) has microsecond resolution,
|
114 |
+
# so the division doesn't require casting all the way to nanos,
|
115 |
+
# so succeeds
|
116 |
+
res = other.to_pytimedelta() / td
|
117 |
+
expected = other.to_pytimedelta() / td.to_pytimedelta()
|
118 |
+
assert res == expected
|
119 |
+
|
120 |
+
# if there's no overflow, we cast to the higher reso
|
121 |
+
left = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_us.value)
|
122 |
+
right = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_ms.value)
|
123 |
+
result = left / right
|
124 |
+
assert result == 0.001
|
125 |
+
|
126 |
+
result = right / left
|
127 |
+
assert result == 1000
|
128 |
+
|
129 |
+
def test_truediv_numeric(self, td):
|
130 |
+
assert td / np.nan is NaT
|
131 |
+
|
132 |
+
res = td / 2
|
133 |
+
assert res._value == td._value / 2
|
134 |
+
assert res._creso == td._creso
|
135 |
+
|
136 |
+
res = td / 2.0
|
137 |
+
assert res._value == td._value / 2
|
138 |
+
assert res._creso == td._creso
|
139 |
+
|
140 |
+
def test_floordiv_timedeltalike(self, td):
|
141 |
+
assert td // td == 1
|
142 |
+
assert (2.5 * td) // td == 2
|
143 |
+
|
144 |
+
other = Timedelta(td._value)
|
145 |
+
msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"
|
146 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
147 |
+
td // other
|
148 |
+
|
149 |
+
# Timedelta(other.to_pytimedelta()) has microsecond resolution,
|
150 |
+
# so the floordiv doesn't require casting all the way to nanos,
|
151 |
+
# so succeeds
|
152 |
+
res = other.to_pytimedelta() // td
|
153 |
+
assert res == 0
|
154 |
+
|
155 |
+
# if there's no overflow, we cast to the higher reso
|
156 |
+
left = Timedelta._from_value_and_reso(50050, NpyDatetimeUnit.NPY_FR_us.value)
|
157 |
+
right = Timedelta._from_value_and_reso(50, NpyDatetimeUnit.NPY_FR_ms.value)
|
158 |
+
result = left // right
|
159 |
+
assert result == 1
|
160 |
+
result = right // left
|
161 |
+
assert result == 0
|
162 |
+
|
163 |
+
def test_floordiv_numeric(self, td):
|
164 |
+
assert td // np.nan is NaT
|
165 |
+
|
166 |
+
res = td // 2
|
167 |
+
assert res._value == td._value // 2
|
168 |
+
assert res._creso == td._creso
|
169 |
+
|
170 |
+
res = td // 2.0
|
171 |
+
assert res._value == td._value // 2
|
172 |
+
assert res._creso == td._creso
|
173 |
+
|
174 |
+
assert td // np.array(np.nan) is NaT
|
175 |
+
|
176 |
+
res = td // np.array(2)
|
177 |
+
assert res._value == td._value // 2
|
178 |
+
assert res._creso == td._creso
|
179 |
+
|
180 |
+
res = td // np.array(2.0)
|
181 |
+
assert res._value == td._value // 2
|
182 |
+
assert res._creso == td._creso
|
183 |
+
|
184 |
+
def test_addsub_mismatched_reso(self, td):
|
185 |
+
# need to cast to since td is out of bounds for ns, so
|
186 |
+
# so we would raise OverflowError without casting
|
187 |
+
other = Timedelta(days=1).as_unit("us")
|
188 |
+
|
189 |
+
# td is out of bounds for ns
|
190 |
+
result = td + other
|
191 |
+
assert result._creso == other._creso
|
192 |
+
assert result.days == td.days + 1
|
193 |
+
|
194 |
+
result = other + td
|
195 |
+
assert result._creso == other._creso
|
196 |
+
assert result.days == td.days + 1
|
197 |
+
|
198 |
+
result = td - other
|
199 |
+
assert result._creso == other._creso
|
200 |
+
assert result.days == td.days - 1
|
201 |
+
|
202 |
+
result = other - td
|
203 |
+
assert result._creso == other._creso
|
204 |
+
assert result.days == 1 - td.days
|
205 |
+
|
206 |
+
other2 = Timedelta(500)
|
207 |
+
msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"
|
208 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
209 |
+
td + other2
|
210 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
211 |
+
other2 + td
|
212 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
213 |
+
td - other2
|
214 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
215 |
+
other2 - td
|
216 |
+
|
217 |
+
def test_min(self, td):
|
218 |
+
assert td.min <= td
|
219 |
+
assert td.min._creso == td._creso
|
220 |
+
assert td.min._value == NaT._value + 1
|
221 |
+
|
222 |
+
def test_max(self, td):
|
223 |
+
assert td.max >= td
|
224 |
+
assert td.max._creso == td._creso
|
225 |
+
assert td.max._value == np.iinfo(np.int64).max
|
226 |
+
|
227 |
+
def test_resolution(self, td):
|
228 |
+
expected = Timedelta._from_value_and_reso(1, td._creso)
|
229 |
+
result = td.resolution
|
230 |
+
assert result == expected
|
231 |
+
assert result._creso == expected._creso
|
232 |
+
|
233 |
+
def test_hash(self) -> None:
|
234 |
+
# GH#54037
|
235 |
+
second_resolution_max = Timedelta(0).as_unit("s").max
|
236 |
+
|
237 |
+
assert hash(second_resolution_max)
|
238 |
+
|
239 |
+
|
240 |
+
def test_timedelta_class_min_max_resolution():
|
241 |
+
# when accessed on the class (as opposed to an instance), we default
|
242 |
+
# to nanoseconds
|
243 |
+
assert Timedelta.min == Timedelta(NaT._value + 1)
|
244 |
+
assert Timedelta.min._creso == NpyDatetimeUnit.NPY_FR_ns.value
|
245 |
+
|
246 |
+
assert Timedelta.max == Timedelta(np.iinfo(np.int64).max)
|
247 |
+
assert Timedelta.max._creso == NpyDatetimeUnit.NPY_FR_ns.value
|
248 |
+
|
249 |
+
assert Timedelta.resolution == Timedelta(1)
|
250 |
+
assert Timedelta.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value
|
251 |
+
|
252 |
+
|
253 |
+
class TestTimedeltaUnaryOps:
|
254 |
+
def test_invert(self):
|
255 |
+
td = Timedelta(10, unit="d")
|
256 |
+
|
257 |
+
msg = "bad operand type for unary ~"
|
258 |
+
with pytest.raises(TypeError, match=msg):
|
259 |
+
~td
|
260 |
+
|
261 |
+
# check this matches pytimedelta and timedelta64
|
262 |
+
with pytest.raises(TypeError, match=msg):
|
263 |
+
~(td.to_pytimedelta())
|
264 |
+
|
265 |
+
umsg = "ufunc 'invert' not supported for the input types"
|
266 |
+
with pytest.raises(TypeError, match=umsg):
|
267 |
+
~(td.to_timedelta64())
|
268 |
+
|
269 |
+
def test_unary_ops(self):
|
270 |
+
td = Timedelta(10, unit="d")
|
271 |
+
|
272 |
+
# __neg__, __pos__
|
273 |
+
assert -td == Timedelta(-10, unit="d")
|
274 |
+
assert -td == Timedelta("-10d")
|
275 |
+
assert +td == Timedelta(10, unit="d")
|
276 |
+
|
277 |
+
# __abs__, __abs__(__neg__)
|
278 |
+
assert abs(td) == td
|
279 |
+
assert abs(-td) == td
|
280 |
+
assert abs(-td) == Timedelta("10d")
|
281 |
+
|
282 |
+
|
283 |
+
class TestTimedeltas:
|
284 |
+
@pytest.mark.parametrize(
|
285 |
+
"unit, value, expected",
|
286 |
+
[
|
287 |
+
("us", 9.999, 9999),
|
288 |
+
("ms", 9.999999, 9999999),
|
289 |
+
("s", 9.999999999, 9999999999),
|
290 |
+
],
|
291 |
+
)
|
292 |
+
def test_rounding_on_int_unit_construction(self, unit, value, expected):
|
293 |
+
# GH 12690
|
294 |
+
result = Timedelta(value, unit=unit)
|
295 |
+
assert result._value == expected
|
296 |
+
result = Timedelta(str(value) + unit)
|
297 |
+
assert result._value == expected
|
298 |
+
|
299 |
+
def test_total_seconds_scalar(self):
|
300 |
+
# see gh-10939
|
301 |
+
rng = Timedelta("1 days, 10:11:12.100123456")
|
302 |
+
expt = 1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456.0 / 1e9
|
303 |
+
tm.assert_almost_equal(rng.total_seconds(), expt)
|
304 |
+
|
305 |
+
rng = Timedelta(np.nan)
|
306 |
+
assert np.isnan(rng.total_seconds())
|
307 |
+
|
308 |
+
def test_conversion(self):
|
309 |
+
for td in [Timedelta(10, unit="d"), Timedelta("1 days, 10:11:12.012345")]:
|
310 |
+
pydt = td.to_pytimedelta()
|
311 |
+
assert td == Timedelta(pydt)
|
312 |
+
assert td == pydt
|
313 |
+
assert isinstance(pydt, timedelta) and not isinstance(pydt, Timedelta)
|
314 |
+
|
315 |
+
assert td == np.timedelta64(td._value, "ns")
|
316 |
+
td64 = td.to_timedelta64()
|
317 |
+
|
318 |
+
assert td64 == np.timedelta64(td._value, "ns")
|
319 |
+
assert td == td64
|
320 |
+
|
321 |
+
assert isinstance(td64, np.timedelta64)
|
322 |
+
|
323 |
+
# this is NOT equal and cannot be roundtripped (because of the nanos)
|
324 |
+
td = Timedelta("1 days, 10:11:12.012345678")
|
325 |
+
assert td != td.to_pytimedelta()
|
326 |
+
|
327 |
+
def test_fields(self):
|
328 |
+
def check(value):
|
329 |
+
# that we are int
|
330 |
+
assert isinstance(value, int)
|
331 |
+
|
332 |
+
# compat to datetime.timedelta
|
333 |
+
rng = to_timedelta("1 days, 10:11:12")
|
334 |
+
assert rng.days == 1
|
335 |
+
assert rng.seconds == 10 * 3600 + 11 * 60 + 12
|
336 |
+
assert rng.microseconds == 0
|
337 |
+
assert rng.nanoseconds == 0
|
338 |
+
|
339 |
+
msg = "'Timedelta' object has no attribute '{}'"
|
340 |
+
with pytest.raises(AttributeError, match=msg.format("hours")):
|
341 |
+
rng.hours
|
342 |
+
with pytest.raises(AttributeError, match=msg.format("minutes")):
|
343 |
+
rng.minutes
|
344 |
+
with pytest.raises(AttributeError, match=msg.format("milliseconds")):
|
345 |
+
rng.milliseconds
|
346 |
+
|
347 |
+
# GH 10050
|
348 |
+
check(rng.days)
|
349 |
+
check(rng.seconds)
|
350 |
+
check(rng.microseconds)
|
351 |
+
check(rng.nanoseconds)
|
352 |
+
|
353 |
+
td = Timedelta("-1 days, 10:11:12")
|
354 |
+
assert abs(td) == Timedelta("13:48:48")
|
355 |
+
assert str(td) == "-1 days +10:11:12"
|
356 |
+
assert -td == Timedelta("0 days 13:48:48")
|
357 |
+
assert -Timedelta("-1 days, 10:11:12")._value == 49728000000000
|
358 |
+
assert Timedelta("-1 days, 10:11:12")._value == -49728000000000
|
359 |
+
|
360 |
+
rng = to_timedelta("-1 days, 10:11:12.100123456")
|
361 |
+
assert rng.days == -1
|
362 |
+
assert rng.seconds == 10 * 3600 + 11 * 60 + 12
|
363 |
+
assert rng.microseconds == 100 * 1000 + 123
|
364 |
+
assert rng.nanoseconds == 456
|
365 |
+
msg = "'Timedelta' object has no attribute '{}'"
|
366 |
+
with pytest.raises(AttributeError, match=msg.format("hours")):
|
367 |
+
rng.hours
|
368 |
+
with pytest.raises(AttributeError, match=msg.format("minutes")):
|
369 |
+
rng.minutes
|
370 |
+
with pytest.raises(AttributeError, match=msg.format("milliseconds")):
|
371 |
+
rng.milliseconds
|
372 |
+
|
373 |
+
# components
|
374 |
+
tup = to_timedelta(-1, "us").components
|
375 |
+
assert tup.days == -1
|
376 |
+
assert tup.hours == 23
|
377 |
+
assert tup.minutes == 59
|
378 |
+
assert tup.seconds == 59
|
379 |
+
assert tup.milliseconds == 999
|
380 |
+
assert tup.microseconds == 999
|
381 |
+
assert tup.nanoseconds == 0
|
382 |
+
|
383 |
+
# GH 10050
|
384 |
+
check(tup.days)
|
385 |
+
check(tup.hours)
|
386 |
+
check(tup.minutes)
|
387 |
+
check(tup.seconds)
|
388 |
+
check(tup.milliseconds)
|
389 |
+
check(tup.microseconds)
|
390 |
+
check(tup.nanoseconds)
|
391 |
+
|
392 |
+
tup = Timedelta("-1 days 1 us").components
|
393 |
+
assert tup.days == -2
|
394 |
+
assert tup.hours == 23
|
395 |
+
assert tup.minutes == 59
|
396 |
+
assert tup.seconds == 59
|
397 |
+
assert tup.milliseconds == 999
|
398 |
+
assert tup.microseconds == 999
|
399 |
+
assert tup.nanoseconds == 0
|
400 |
+
|
401 |
+
# TODO: this is a test of to_timedelta string parsing
|
402 |
+
def test_iso_conversion(self):
|
403 |
+
# GH #21877
|
404 |
+
expected = Timedelta(1, unit="s")
|
405 |
+
assert to_timedelta("P0DT0H0M1S") == expected
|
406 |
+
|
407 |
+
# TODO: this is a test of to_timedelta returning NaT
|
408 |
+
def test_nat_converters(self):
|
409 |
+
result = to_timedelta("nat").to_numpy()
|
410 |
+
assert result.dtype.kind == "M"
|
411 |
+
assert result.astype("int64") == iNaT
|
412 |
+
|
413 |
+
result = to_timedelta("nan").to_numpy()
|
414 |
+
assert result.dtype.kind == "M"
|
415 |
+
assert result.astype("int64") == iNaT
|
416 |
+
|
417 |
+
def test_numeric_conversions(self):
|
418 |
+
assert Timedelta(0) == np.timedelta64(0, "ns")
|
419 |
+
assert Timedelta(10) == np.timedelta64(10, "ns")
|
420 |
+
assert Timedelta(10, unit="ns") == np.timedelta64(10, "ns")
|
421 |
+
|
422 |
+
assert Timedelta(10, unit="us") == np.timedelta64(10, "us")
|
423 |
+
assert Timedelta(10, unit="ms") == np.timedelta64(10, "ms")
|
424 |
+
assert Timedelta(10, unit="s") == np.timedelta64(10, "s")
|
425 |
+
assert Timedelta(10, unit="d") == np.timedelta64(10, "D")
|
426 |
+
|
427 |
+
def test_timedelta_conversions(self):
|
428 |
+
assert Timedelta(timedelta(seconds=1)) == np.timedelta64(1, "s").astype(
|
429 |
+
"m8[ns]"
|
430 |
+
)
|
431 |
+
assert Timedelta(timedelta(microseconds=1)) == np.timedelta64(1, "us").astype(
|
432 |
+
"m8[ns]"
|
433 |
+
)
|
434 |
+
assert Timedelta(timedelta(days=1)) == np.timedelta64(1, "D").astype("m8[ns]")
|
435 |
+
|
436 |
+
def test_to_numpy_alias(self):
|
437 |
+
# GH 24653: alias .to_numpy() for scalars
|
438 |
+
td = Timedelta("10m7s")
|
439 |
+
assert td.to_timedelta64() == td.to_numpy()
|
440 |
+
|
441 |
+
# GH#44460
|
442 |
+
msg = "dtype and copy arguments are ignored"
|
443 |
+
with pytest.raises(ValueError, match=msg):
|
444 |
+
td.to_numpy("m8[s]")
|
445 |
+
with pytest.raises(ValueError, match=msg):
|
446 |
+
td.to_numpy(copy=True)
|
447 |
+
|
448 |
+
def test_identity(self):
|
449 |
+
td = Timedelta(10, unit="d")
|
450 |
+
assert isinstance(td, Timedelta)
|
451 |
+
assert isinstance(td, timedelta)
|
452 |
+
|
453 |
+
def test_short_format_converters(self):
|
454 |
+
def conv(v):
|
455 |
+
return v.astype("m8[ns]")
|
456 |
+
|
457 |
+
assert Timedelta("10") == np.timedelta64(10, "ns")
|
458 |
+
assert Timedelta("10ns") == np.timedelta64(10, "ns")
|
459 |
+
assert Timedelta("100") == np.timedelta64(100, "ns")
|
460 |
+
assert Timedelta("100ns") == np.timedelta64(100, "ns")
|
461 |
+
|
462 |
+
assert Timedelta("1000") == np.timedelta64(1000, "ns")
|
463 |
+
assert Timedelta("1000ns") == np.timedelta64(1000, "ns")
|
464 |
+
assert Timedelta("1000NS") == np.timedelta64(1000, "ns")
|
465 |
+
|
466 |
+
assert Timedelta("10us") == np.timedelta64(10000, "ns")
|
467 |
+
assert Timedelta("100us") == np.timedelta64(100000, "ns")
|
468 |
+
assert Timedelta("1000us") == np.timedelta64(1000000, "ns")
|
469 |
+
assert Timedelta("1000Us") == np.timedelta64(1000000, "ns")
|
470 |
+
assert Timedelta("1000uS") == np.timedelta64(1000000, "ns")
|
471 |
+
|
472 |
+
assert Timedelta("1ms") == np.timedelta64(1000000, "ns")
|
473 |
+
assert Timedelta("10ms") == np.timedelta64(10000000, "ns")
|
474 |
+
assert Timedelta("100ms") == np.timedelta64(100000000, "ns")
|
475 |
+
assert Timedelta("1000ms") == np.timedelta64(1000000000, "ns")
|
476 |
+
|
477 |
+
assert Timedelta("-1s") == -np.timedelta64(1000000000, "ns")
|
478 |
+
assert Timedelta("1s") == np.timedelta64(1000000000, "ns")
|
479 |
+
assert Timedelta("10s") == np.timedelta64(10000000000, "ns")
|
480 |
+
assert Timedelta("100s") == np.timedelta64(100000000000, "ns")
|
481 |
+
assert Timedelta("1000s") == np.timedelta64(1000000000000, "ns")
|
482 |
+
|
483 |
+
assert Timedelta("1d") == conv(np.timedelta64(1, "D"))
|
484 |
+
assert Timedelta("-1d") == -conv(np.timedelta64(1, "D"))
|
485 |
+
assert Timedelta("1D") == conv(np.timedelta64(1, "D"))
|
486 |
+
assert Timedelta("10D") == conv(np.timedelta64(10, "D"))
|
487 |
+
assert Timedelta("100D") == conv(np.timedelta64(100, "D"))
|
488 |
+
assert Timedelta("1000D") == conv(np.timedelta64(1000, "D"))
|
489 |
+
assert Timedelta("10000D") == conv(np.timedelta64(10000, "D"))
|
490 |
+
|
491 |
+
# space
|
492 |
+
assert Timedelta(" 10000D ") == conv(np.timedelta64(10000, "D"))
|
493 |
+
assert Timedelta(" - 10000D ") == -conv(np.timedelta64(10000, "D"))
|
494 |
+
|
495 |
+
# invalid
|
496 |
+
msg = "invalid unit abbreviation"
|
497 |
+
with pytest.raises(ValueError, match=msg):
|
498 |
+
Timedelta("1foo")
|
499 |
+
msg = "unit abbreviation w/o a number"
|
500 |
+
with pytest.raises(ValueError, match=msg):
|
501 |
+
Timedelta("foo")
|
502 |
+
|
503 |
+
def test_full_format_converters(self):
|
504 |
+
def conv(v):
|
505 |
+
return v.astype("m8[ns]")
|
506 |
+
|
507 |
+
d1 = np.timedelta64(1, "D")
|
508 |
+
|
509 |
+
assert Timedelta("1days") == conv(d1)
|
510 |
+
assert Timedelta("1days,") == conv(d1)
|
511 |
+
assert Timedelta("- 1days,") == -conv(d1)
|
512 |
+
|
513 |
+
assert Timedelta("00:00:01") == conv(np.timedelta64(1, "s"))
|
514 |
+
assert Timedelta("06:00:01") == conv(np.timedelta64(6 * 3600 + 1, "s"))
|
515 |
+
assert Timedelta("06:00:01.0") == conv(np.timedelta64(6 * 3600 + 1, "s"))
|
516 |
+
assert Timedelta("06:00:01.01") == conv(
|
517 |
+
np.timedelta64(1000 * (6 * 3600 + 1) + 10, "ms")
|
518 |
+
)
|
519 |
+
|
520 |
+
assert Timedelta("- 1days, 00:00:01") == conv(-d1 + np.timedelta64(1, "s"))
|
521 |
+
assert Timedelta("1days, 06:00:01") == conv(
|
522 |
+
d1 + np.timedelta64(6 * 3600 + 1, "s")
|
523 |
+
)
|
524 |
+
assert Timedelta("1days, 06:00:01.01") == conv(
|
525 |
+
d1 + np.timedelta64(1000 * (6 * 3600 + 1) + 10, "ms")
|
526 |
+
)
|
527 |
+
|
528 |
+
# invalid
|
529 |
+
msg = "have leftover units"
|
530 |
+
with pytest.raises(ValueError, match=msg):
|
531 |
+
Timedelta("- 1days, 00")
|
532 |
+
|
533 |
+
def test_pickle(self):
|
534 |
+
v = Timedelta("1 days 10:11:12.0123456")
|
535 |
+
v_p = tm.round_trip_pickle(v)
|
536 |
+
assert v == v_p
|
537 |
+
|
538 |
+
def test_timedelta_hash_equality(self):
|
539 |
+
# GH 11129
|
540 |
+
v = Timedelta(1, "D")
|
541 |
+
td = timedelta(days=1)
|
542 |
+
assert hash(v) == hash(td)
|
543 |
+
|
544 |
+
d = {td: 2}
|
545 |
+
assert d[v] == 2
|
546 |
+
|
547 |
+
tds = [Timedelta(seconds=1) + Timedelta(days=n) for n in range(20)]
|
548 |
+
assert all(hash(td) == hash(td.to_pytimedelta()) for td in tds)
|
549 |
+
|
550 |
+
# python timedeltas drop ns resolution
|
551 |
+
ns_td = Timedelta(1, "ns")
|
552 |
+
assert hash(ns_td) != hash(ns_td.to_pytimedelta())
|
553 |
+
|
554 |
+
@pytest.mark.skip_ubsan
|
555 |
+
@pytest.mark.xfail(
|
556 |
+
reason="pd.Timedelta violates the Python hash invariant (GH#44504).",
|
557 |
+
)
|
558 |
+
@given(
|
559 |
+
st.integers(
|
560 |
+
min_value=(-sys.maxsize - 1) // 500,
|
561 |
+
max_value=sys.maxsize // 500,
|
562 |
+
)
|
563 |
+
)
|
564 |
+
def test_hash_equality_invariance(self, half_microseconds: int) -> None:
|
565 |
+
# GH#44504
|
566 |
+
|
567 |
+
nanoseconds = half_microseconds * 500
|
568 |
+
|
569 |
+
pandas_timedelta = Timedelta(nanoseconds)
|
570 |
+
numpy_timedelta = np.timedelta64(nanoseconds)
|
571 |
+
|
572 |
+
# See: https://docs.python.org/3/glossary.html#term-hashable
|
573 |
+
# Hashable objects which compare equal must have the same hash value.
|
574 |
+
assert pandas_timedelta != numpy_timedelta or hash(pandas_timedelta) == hash(
|
575 |
+
numpy_timedelta
|
576 |
+
)
|
577 |
+
|
578 |
+
def test_implementation_limits(self):
|
579 |
+
min_td = Timedelta(Timedelta.min)
|
580 |
+
max_td = Timedelta(Timedelta.max)
|
581 |
+
|
582 |
+
# GH 12727
|
583 |
+
# timedelta limits correspond to int64 boundaries
|
584 |
+
assert min_td._value == iNaT + 1
|
585 |
+
assert max_td._value == lib.i8max
|
586 |
+
|
587 |
+
# Beyond lower limit, a NAT before the Overflow
|
588 |
+
assert (min_td - Timedelta(1, "ns")) is NaT
|
589 |
+
|
590 |
+
msg = "int too (large|big) to convert"
|
591 |
+
with pytest.raises(OverflowError, match=msg):
|
592 |
+
min_td - Timedelta(2, "ns")
|
593 |
+
|
594 |
+
with pytest.raises(OverflowError, match=msg):
|
595 |
+
max_td + Timedelta(1, "ns")
|
596 |
+
|
597 |
+
# Same tests using the internal nanosecond values
|
598 |
+
td = Timedelta(min_td._value - 1, "ns")
|
599 |
+
assert td is NaT
|
600 |
+
|
601 |
+
msg = "Cannot cast -9223372036854775809 from ns to 'ns' without overflow"
|
602 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
603 |
+
Timedelta(min_td._value - 2, "ns")
|
604 |
+
|
605 |
+
msg = "Cannot cast 9223372036854775808 from ns to 'ns' without overflow"
|
606 |
+
with pytest.raises(OutOfBoundsTimedelta, match=msg):
|
607 |
+
Timedelta(max_td._value + 1, "ns")
|
608 |
+
|
609 |
+
def test_total_seconds_precision(self):
|
610 |
+
# GH 19458
|
611 |
+
assert Timedelta("30s").total_seconds() == 30.0
|
612 |
+
assert Timedelta("0").total_seconds() == 0.0
|
613 |
+
assert Timedelta("-2s").total_seconds() == -2.0
|
614 |
+
assert Timedelta("5.324s").total_seconds() == 5.324
|
615 |
+
assert (Timedelta("30s").total_seconds() - 30.0) < 1e-20
|
616 |
+
assert (30.0 - Timedelta("30s").total_seconds()) < 1e-20
|
617 |
+
|
618 |
+
def test_resolution_string(self):
|
619 |
+
assert Timedelta(days=1).resolution_string == "D"
|
620 |
+
assert Timedelta(days=1, hours=6).resolution_string == "h"
|
621 |
+
assert Timedelta(days=1, minutes=6).resolution_string == "min"
|
622 |
+
assert Timedelta(days=1, seconds=6).resolution_string == "s"
|
623 |
+
assert Timedelta(days=1, milliseconds=6).resolution_string == "ms"
|
624 |
+
assert Timedelta(days=1, microseconds=6).resolution_string == "us"
|
625 |
+
assert Timedelta(days=1, nanoseconds=6).resolution_string == "ns"
|
626 |
+
|
627 |
+
def test_resolution_deprecated(self):
|
628 |
+
# GH#21344
|
629 |
+
td = Timedelta(days=4, hours=3)
|
630 |
+
result = td.resolution
|
631 |
+
assert result == Timedelta(nanoseconds=1)
|
632 |
+
|
633 |
+
# Check that the attribute is available on the class, mirroring
|
634 |
+
# the stdlib timedelta behavior
|
635 |
+
result = Timedelta.resolution
|
636 |
+
assert result == Timedelta(nanoseconds=1)
|
637 |
+
|
638 |
+
|
639 |
+
@pytest.mark.parametrize(
|
640 |
+
"value, expected",
|
641 |
+
[
|
642 |
+
(Timedelta("10s"), True),
|
643 |
+
(Timedelta("-10s"), True),
|
644 |
+
(Timedelta(10, unit="ns"), True),
|
645 |
+
(Timedelta(0, unit="ns"), False),
|
646 |
+
(Timedelta(-10, unit="ns"), True),
|
647 |
+
(Timedelta(None), True),
|
648 |
+
(NaT, True),
|
649 |
+
],
|
650 |
+
)
|
651 |
+
def test_truthiness(value, expected):
|
652 |
+
# https://github.com/pandas-dev/pandas/issues/21484
|
653 |
+
assert bool(value) is expected
|
654 |
+
|
655 |
+
|
656 |
+
def test_timedelta_attribute_precision():
|
657 |
+
# GH 31354
|
658 |
+
td = Timedelta(1552211999999999872, unit="ns")
|
659 |
+
result = td.days * 86400
|
660 |
+
result += td.seconds
|
661 |
+
result *= 1000000
|
662 |
+
result += td.microseconds
|
663 |
+
result *= 1000
|
664 |
+
result += td.nanoseconds
|
665 |
+
expected = td._value
|
666 |
+
assert result == expected
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (202 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_arithmetic.cpython-310.pyc
ADDED
Binary file (10.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-310.pyc
ADDED
Binary file (8.69 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-310.pyc
ADDED
Binary file (31.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-310.pyc
ADDED
Binary file (5.93 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timestamp.cpython-310.pyc
ADDED
Binary file (25.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-310.pyc
ADDED
Binary file (1.05 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (210 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_as_unit.cpython-310.pyc
ADDED
Binary file (2.72 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_normalize.cpython-310.pyc
ADDED
Binary file (1.28 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_replace.cpython-310.pyc
ADDED
Binary file (6.64 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_round.cpython-310.pyc
ADDED
Binary file (10.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_timestamp_method.cpython-310.pyc
ADDED
Binary file (1.11 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_to_julian_date.cpython-310.pyc
ADDED
Binary file (1.36 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_to_pydatetime.cpython-310.pyc
ADDED
Binary file (3.19 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_convert.cpython-310.pyc
ADDED
Binary file (1.85 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/__pycache__/test_tz_localize.cpython-310.pyc
ADDED
Binary file (9.71 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_as_unit.py
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
4 |
+
from pandas.errors import OutOfBoundsDatetime
|
5 |
+
|
6 |
+
from pandas import Timestamp
|
7 |
+
|
8 |
+
|
9 |
+
class TestTimestampAsUnit:
|
10 |
+
def test_as_unit(self):
|
11 |
+
ts = Timestamp("1970-01-01").as_unit("ns")
|
12 |
+
assert ts.unit == "ns"
|
13 |
+
|
14 |
+
assert ts.as_unit("ns") is ts
|
15 |
+
|
16 |
+
res = ts.as_unit("us")
|
17 |
+
assert res._value == ts._value // 1000
|
18 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_us.value
|
19 |
+
|
20 |
+
rt = res.as_unit("ns")
|
21 |
+
assert rt._value == ts._value
|
22 |
+
assert rt._creso == ts._creso
|
23 |
+
|
24 |
+
res = ts.as_unit("ms")
|
25 |
+
assert res._value == ts._value // 1_000_000
|
26 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
27 |
+
|
28 |
+
rt = res.as_unit("ns")
|
29 |
+
assert rt._value == ts._value
|
30 |
+
assert rt._creso == ts._creso
|
31 |
+
|
32 |
+
res = ts.as_unit("s")
|
33 |
+
assert res._value == ts._value // 1_000_000_000
|
34 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_s.value
|
35 |
+
|
36 |
+
rt = res.as_unit("ns")
|
37 |
+
assert rt._value == ts._value
|
38 |
+
assert rt._creso == ts._creso
|
39 |
+
|
40 |
+
def test_as_unit_overflows(self):
|
41 |
+
# microsecond that would be just out of bounds for nano
|
42 |
+
us = 9223372800000000
|
43 |
+
ts = Timestamp._from_value_and_reso(us, NpyDatetimeUnit.NPY_FR_us.value, None)
|
44 |
+
|
45 |
+
msg = "Cannot cast 2262-04-12 00:00:00 to unit='ns' without overflow"
|
46 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
47 |
+
ts.as_unit("ns")
|
48 |
+
|
49 |
+
res = ts.as_unit("ms")
|
50 |
+
assert res._value == us // 1000
|
51 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
52 |
+
|
53 |
+
def test_as_unit_rounding(self):
|
54 |
+
ts = Timestamp(1_500_000) # i.e. 1500 microseconds
|
55 |
+
res = ts.as_unit("ms")
|
56 |
+
|
57 |
+
expected = Timestamp(1_000_000) # i.e. 1 millisecond
|
58 |
+
assert res == expected
|
59 |
+
|
60 |
+
assert res._creso == NpyDatetimeUnit.NPY_FR_ms.value
|
61 |
+
assert res._value == 1
|
62 |
+
|
63 |
+
with pytest.raises(ValueError, match="Cannot losslessly convert units"):
|
64 |
+
ts.as_unit("ms", round_ok=False)
|
65 |
+
|
66 |
+
def test_as_unit_non_nano(self):
|
67 |
+
# case where we are going neither to nor from nano
|
68 |
+
ts = Timestamp("1970-01-02").as_unit("ms")
|
69 |
+
assert ts.year == 1970
|
70 |
+
assert ts.month == 1
|
71 |
+
assert ts.day == 2
|
72 |
+
assert ts.hour == ts.minute == ts.second == ts.microsecond == ts.nanosecond == 0
|
73 |
+
|
74 |
+
res = ts.as_unit("s")
|
75 |
+
assert res._value == 24 * 3600
|
76 |
+
assert res.year == 1970
|
77 |
+
assert res.month == 1
|
78 |
+
assert res.day == 2
|
79 |
+
assert (
|
80 |
+
res.hour
|
81 |
+
== res.minute
|
82 |
+
== res.second
|
83 |
+
== res.microsecond
|
84 |
+
== res.nanosecond
|
85 |
+
== 0
|
86 |
+
)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_normalize.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
|
3 |
+
from pandas._libs.tslibs import Timestamp
|
4 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
5 |
+
|
6 |
+
|
7 |
+
class TestTimestampNormalize:
|
8 |
+
@pytest.mark.parametrize("arg", ["2013-11-30", "2013-11-30 12:00:00"])
|
9 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
10 |
+
def test_normalize(self, tz_naive_fixture, arg, unit):
|
11 |
+
tz = tz_naive_fixture
|
12 |
+
ts = Timestamp(arg, tz=tz).as_unit(unit)
|
13 |
+
result = ts.normalize()
|
14 |
+
expected = Timestamp("2013-11-30", tz=tz)
|
15 |
+
assert result == expected
|
16 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
17 |
+
|
18 |
+
def test_normalize_pre_epoch_dates(self):
|
19 |
+
# GH: 36294
|
20 |
+
result = Timestamp("1969-01-01 09:00:00").normalize()
|
21 |
+
expected = Timestamp("1969-01-01 00:00:00")
|
22 |
+
assert result == expected
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_replace.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
|
3 |
+
from dateutil.tz import gettz
|
4 |
+
import numpy as np
|
5 |
+
import pytest
|
6 |
+
import pytz
|
7 |
+
|
8 |
+
from pandas._libs.tslibs import (
|
9 |
+
OutOfBoundsDatetime,
|
10 |
+
Timestamp,
|
11 |
+
conversion,
|
12 |
+
)
|
13 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
14 |
+
import pandas.util._test_decorators as td
|
15 |
+
|
16 |
+
import pandas._testing as tm
|
17 |
+
|
18 |
+
|
19 |
+
class TestTimestampReplace:
|
20 |
+
def test_replace_out_of_pydatetime_bounds(self):
|
21 |
+
# GH#50348
|
22 |
+
ts = Timestamp("2016-01-01").as_unit("ns")
|
23 |
+
|
24 |
+
msg = "Out of bounds timestamp: 99999-01-01 00:00:00 with frequency 'ns'"
|
25 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
26 |
+
ts.replace(year=99_999)
|
27 |
+
|
28 |
+
ts = ts.as_unit("ms")
|
29 |
+
result = ts.replace(year=99_999)
|
30 |
+
assert result.year == 99_999
|
31 |
+
assert result._value == Timestamp(np.datetime64("99999-01-01", "ms"))._value
|
32 |
+
|
33 |
+
def test_replace_non_nano(self):
|
34 |
+
ts = Timestamp._from_value_and_reso(
|
35 |
+
91514880000000000, NpyDatetimeUnit.NPY_FR_us.value, None
|
36 |
+
)
|
37 |
+
assert ts.to_pydatetime() == datetime(4869, 12, 28)
|
38 |
+
|
39 |
+
result = ts.replace(year=4900)
|
40 |
+
assert result._creso == ts._creso
|
41 |
+
assert result.to_pydatetime() == datetime(4900, 12, 28)
|
42 |
+
|
43 |
+
def test_replace_naive(self):
|
44 |
+
# GH#14621, GH#7825
|
45 |
+
ts = Timestamp("2016-01-01 09:00:00")
|
46 |
+
result = ts.replace(hour=0)
|
47 |
+
expected = Timestamp("2016-01-01 00:00:00")
|
48 |
+
assert result == expected
|
49 |
+
|
50 |
+
def test_replace_aware(self, tz_aware_fixture):
|
51 |
+
tz = tz_aware_fixture
|
52 |
+
# GH#14621, GH#7825
|
53 |
+
# replacing datetime components with and w/o presence of a timezone
|
54 |
+
ts = Timestamp("2016-01-01 09:00:00", tz=tz)
|
55 |
+
result = ts.replace(hour=0)
|
56 |
+
expected = Timestamp("2016-01-01 00:00:00", tz=tz)
|
57 |
+
assert result == expected
|
58 |
+
|
59 |
+
def test_replace_preserves_nanos(self, tz_aware_fixture):
|
60 |
+
tz = tz_aware_fixture
|
61 |
+
# GH#14621, GH#7825
|
62 |
+
ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)
|
63 |
+
result = ts.replace(hour=0)
|
64 |
+
expected = Timestamp("2016-01-01 00:00:00.000000123", tz=tz)
|
65 |
+
assert result == expected
|
66 |
+
|
67 |
+
def test_replace_multiple(self, tz_aware_fixture):
|
68 |
+
tz = tz_aware_fixture
|
69 |
+
# GH#14621, GH#7825
|
70 |
+
# replacing datetime components with and w/o presence of a timezone
|
71 |
+
# test all
|
72 |
+
ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)
|
73 |
+
result = ts.replace(
|
74 |
+
year=2015,
|
75 |
+
month=2,
|
76 |
+
day=2,
|
77 |
+
hour=0,
|
78 |
+
minute=5,
|
79 |
+
second=5,
|
80 |
+
microsecond=5,
|
81 |
+
nanosecond=5,
|
82 |
+
)
|
83 |
+
expected = Timestamp("2015-02-02 00:05:05.000005005", tz=tz)
|
84 |
+
assert result == expected
|
85 |
+
|
86 |
+
def test_replace_invalid_kwarg(self, tz_aware_fixture):
|
87 |
+
tz = tz_aware_fixture
|
88 |
+
# GH#14621, GH#7825
|
89 |
+
ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)
|
90 |
+
msg = r"replace\(\) got an unexpected keyword argument"
|
91 |
+
with pytest.raises(TypeError, match=msg):
|
92 |
+
ts.replace(foo=5)
|
93 |
+
|
94 |
+
def test_replace_integer_args(self, tz_aware_fixture):
|
95 |
+
tz = tz_aware_fixture
|
96 |
+
# GH#14621, GH#7825
|
97 |
+
ts = Timestamp("2016-01-01 09:00:00.000000123", tz=tz)
|
98 |
+
msg = "value must be an integer, received <class 'float'> for hour"
|
99 |
+
with pytest.raises(ValueError, match=msg):
|
100 |
+
ts.replace(hour=0.1)
|
101 |
+
|
102 |
+
def test_replace_tzinfo_equiv_tz_localize_none(self):
|
103 |
+
# GH#14621, GH#7825
|
104 |
+
# assert conversion to naive is the same as replacing tzinfo with None
|
105 |
+
ts = Timestamp("2013-11-03 01:59:59.999999-0400", tz="US/Eastern")
|
106 |
+
assert ts.tz_localize(None) == ts.replace(tzinfo=None)
|
107 |
+
|
108 |
+
@td.skip_if_windows
|
109 |
+
def test_replace_tzinfo(self):
|
110 |
+
# GH#15683
|
111 |
+
dt = datetime(2016, 3, 27, 1)
|
112 |
+
tzinfo = pytz.timezone("CET").localize(dt, is_dst=False).tzinfo
|
113 |
+
|
114 |
+
result_dt = dt.replace(tzinfo=tzinfo)
|
115 |
+
result_pd = Timestamp(dt).replace(tzinfo=tzinfo)
|
116 |
+
|
117 |
+
# datetime.timestamp() converts in the local timezone
|
118 |
+
with tm.set_timezone("UTC"):
|
119 |
+
assert result_dt.timestamp() == result_pd.timestamp()
|
120 |
+
|
121 |
+
assert result_dt == result_pd
|
122 |
+
assert result_dt == result_pd.to_pydatetime()
|
123 |
+
|
124 |
+
result_dt = dt.replace(tzinfo=tzinfo).replace(tzinfo=None)
|
125 |
+
result_pd = Timestamp(dt).replace(tzinfo=tzinfo).replace(tzinfo=None)
|
126 |
+
|
127 |
+
# datetime.timestamp() converts in the local timezone
|
128 |
+
with tm.set_timezone("UTC"):
|
129 |
+
assert result_dt.timestamp() == result_pd.timestamp()
|
130 |
+
|
131 |
+
assert result_dt == result_pd
|
132 |
+
assert result_dt == result_pd.to_pydatetime()
|
133 |
+
|
134 |
+
@pytest.mark.parametrize(
|
135 |
+
"tz, normalize",
|
136 |
+
[
|
137 |
+
(pytz.timezone("US/Eastern"), lambda x: x.tzinfo.normalize(x)),
|
138 |
+
(gettz("US/Eastern"), lambda x: x),
|
139 |
+
],
|
140 |
+
)
|
141 |
+
def test_replace_across_dst(self, tz, normalize):
|
142 |
+
# GH#18319 check that 1) timezone is correctly normalized and
|
143 |
+
# 2) that hour is not incorrectly changed by this normalization
|
144 |
+
ts_naive = Timestamp("2017-12-03 16:03:30")
|
145 |
+
ts_aware = conversion.localize_pydatetime(ts_naive, tz)
|
146 |
+
|
147 |
+
# Preliminary sanity-check
|
148 |
+
assert ts_aware == normalize(ts_aware)
|
149 |
+
|
150 |
+
# Replace across DST boundary
|
151 |
+
ts2 = ts_aware.replace(month=6)
|
152 |
+
|
153 |
+
# Check that `replace` preserves hour literal
|
154 |
+
assert (ts2.hour, ts2.minute) == (ts_aware.hour, ts_aware.minute)
|
155 |
+
|
156 |
+
# Check that post-replace object is appropriately normalized
|
157 |
+
ts2b = normalize(ts2)
|
158 |
+
assert ts2 == ts2b
|
159 |
+
|
160 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
161 |
+
def test_replace_dst_border(self, unit):
|
162 |
+
# Gh 7825
|
163 |
+
t = Timestamp("2013-11-3", tz="America/Chicago").as_unit(unit)
|
164 |
+
result = t.replace(hour=3)
|
165 |
+
expected = Timestamp("2013-11-3 03:00:00", tz="America/Chicago")
|
166 |
+
assert result == expected
|
167 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
168 |
+
|
169 |
+
@pytest.mark.parametrize("fold", [0, 1])
|
170 |
+
@pytest.mark.parametrize("tz", ["dateutil/Europe/London", "Europe/London"])
|
171 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
172 |
+
def test_replace_dst_fold(self, fold, tz, unit):
|
173 |
+
# GH 25017
|
174 |
+
d = datetime(2019, 10, 27, 2, 30)
|
175 |
+
ts = Timestamp(d, tz=tz).as_unit(unit)
|
176 |
+
result = ts.replace(hour=1, fold=fold)
|
177 |
+
expected = Timestamp(datetime(2019, 10, 27, 1, 30)).tz_localize(
|
178 |
+
tz, ambiguous=not fold
|
179 |
+
)
|
180 |
+
assert result == expected
|
181 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
182 |
+
|
183 |
+
@pytest.mark.parametrize("fold", [0, 1])
|
184 |
+
def test_replace_preserves_fold(self, fold):
|
185 |
+
# GH#37610. Check that replace preserves Timestamp fold property
|
186 |
+
tz = gettz("Europe/Moscow")
|
187 |
+
|
188 |
+
ts = Timestamp(
|
189 |
+
year=2009, month=10, day=25, hour=2, minute=30, fold=fold, tzinfo=tz
|
190 |
+
)
|
191 |
+
ts_replaced = ts.replace(second=1)
|
192 |
+
|
193 |
+
assert ts_replaced.fold == fold
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_round.py
ADDED
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from hypothesis import (
|
2 |
+
given,
|
3 |
+
strategies as st,
|
4 |
+
)
|
5 |
+
import numpy as np
|
6 |
+
import pytest
|
7 |
+
import pytz
|
8 |
+
|
9 |
+
from pandas._libs import lib
|
10 |
+
from pandas._libs.tslibs import (
|
11 |
+
NaT,
|
12 |
+
OutOfBoundsDatetime,
|
13 |
+
Timedelta,
|
14 |
+
Timestamp,
|
15 |
+
iNaT,
|
16 |
+
to_offset,
|
17 |
+
)
|
18 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
19 |
+
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
|
20 |
+
|
21 |
+
import pandas._testing as tm
|
22 |
+
|
23 |
+
|
24 |
+
class TestTimestampRound:
|
25 |
+
def test_round_division_by_zero_raises(self):
|
26 |
+
ts = Timestamp("2016-01-01")
|
27 |
+
|
28 |
+
msg = "Division by zero in rounding"
|
29 |
+
with pytest.raises(ValueError, match=msg):
|
30 |
+
ts.round("0ns")
|
31 |
+
|
32 |
+
@pytest.mark.parametrize(
|
33 |
+
"timestamp, freq, expected",
|
34 |
+
[
|
35 |
+
("20130101 09:10:11", "D", "20130101"),
|
36 |
+
("20130101 19:10:11", "D", "20130102"),
|
37 |
+
("20130201 12:00:00", "D", "20130202"),
|
38 |
+
("20130104 12:00:00", "D", "20130105"),
|
39 |
+
("2000-01-05 05:09:15.13", "D", "2000-01-05 00:00:00"),
|
40 |
+
("2000-01-05 05:09:15.13", "h", "2000-01-05 05:00:00"),
|
41 |
+
("2000-01-05 05:09:15.13", "s", "2000-01-05 05:09:15"),
|
42 |
+
],
|
43 |
+
)
|
44 |
+
def test_round_frequencies(self, timestamp, freq, expected):
|
45 |
+
dt = Timestamp(timestamp)
|
46 |
+
result = dt.round(freq)
|
47 |
+
expected = Timestamp(expected)
|
48 |
+
assert result == expected
|
49 |
+
|
50 |
+
def test_round_tzaware(self):
|
51 |
+
dt = Timestamp("20130101 09:10:11", tz="US/Eastern")
|
52 |
+
result = dt.round("D")
|
53 |
+
expected = Timestamp("20130101", tz="US/Eastern")
|
54 |
+
assert result == expected
|
55 |
+
|
56 |
+
dt = Timestamp("20130101 09:10:11", tz="US/Eastern")
|
57 |
+
result = dt.round("s")
|
58 |
+
assert result == dt
|
59 |
+
|
60 |
+
def test_round_30min(self):
|
61 |
+
# round
|
62 |
+
dt = Timestamp("20130104 12:32:00")
|
63 |
+
result = dt.round("30Min")
|
64 |
+
expected = Timestamp("20130104 12:30:00")
|
65 |
+
assert result == expected
|
66 |
+
|
67 |
+
def test_round_subsecond(self):
|
68 |
+
# GH#14440 & GH#15578
|
69 |
+
result = Timestamp("2016-10-17 12:00:00.0015").round("ms")
|
70 |
+
expected = Timestamp("2016-10-17 12:00:00.002000")
|
71 |
+
assert result == expected
|
72 |
+
|
73 |
+
result = Timestamp("2016-10-17 12:00:00.00149").round("ms")
|
74 |
+
expected = Timestamp("2016-10-17 12:00:00.001000")
|
75 |
+
assert result == expected
|
76 |
+
|
77 |
+
ts = Timestamp("2016-10-17 12:00:00.0015")
|
78 |
+
for freq in ["us", "ns"]:
|
79 |
+
assert ts == ts.round(freq)
|
80 |
+
|
81 |
+
result = Timestamp("2016-10-17 12:00:00.001501031").round("10ns")
|
82 |
+
expected = Timestamp("2016-10-17 12:00:00.001501030")
|
83 |
+
assert result == expected
|
84 |
+
|
85 |
+
def test_round_nonstandard_freq(self):
|
86 |
+
with tm.assert_produces_warning(False):
|
87 |
+
Timestamp("2016-10-17 12:00:00.001501031").round("1010ns")
|
88 |
+
|
89 |
+
def test_round_invalid_arg(self):
|
90 |
+
stamp = Timestamp("2000-01-05 05:09:15.13")
|
91 |
+
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
|
92 |
+
stamp.round("foo")
|
93 |
+
|
94 |
+
@pytest.mark.parametrize(
|
95 |
+
"test_input, rounder, freq, expected",
|
96 |
+
[
|
97 |
+
("2117-01-01 00:00:45", "floor", "15s", "2117-01-01 00:00:45"),
|
98 |
+
("2117-01-01 00:00:45", "ceil", "15s", "2117-01-01 00:00:45"),
|
99 |
+
(
|
100 |
+
"2117-01-01 00:00:45.000000012",
|
101 |
+
"floor",
|
102 |
+
"10ns",
|
103 |
+
"2117-01-01 00:00:45.000000010",
|
104 |
+
),
|
105 |
+
(
|
106 |
+
"1823-01-01 00:00:01.000000012",
|
107 |
+
"ceil",
|
108 |
+
"10ns",
|
109 |
+
"1823-01-01 00:00:01.000000020",
|
110 |
+
),
|
111 |
+
("1823-01-01 00:00:01", "floor", "1s", "1823-01-01 00:00:01"),
|
112 |
+
("1823-01-01 00:00:01", "ceil", "1s", "1823-01-01 00:00:01"),
|
113 |
+
("NaT", "floor", "1s", "NaT"),
|
114 |
+
("NaT", "ceil", "1s", "NaT"),
|
115 |
+
],
|
116 |
+
)
|
117 |
+
def test_ceil_floor_edge(self, test_input, rounder, freq, expected):
|
118 |
+
dt = Timestamp(test_input)
|
119 |
+
func = getattr(dt, rounder)
|
120 |
+
result = func(freq)
|
121 |
+
|
122 |
+
if dt is NaT:
|
123 |
+
assert result is NaT
|
124 |
+
else:
|
125 |
+
expected = Timestamp(expected)
|
126 |
+
assert result == expected
|
127 |
+
|
128 |
+
@pytest.mark.parametrize(
|
129 |
+
"test_input, freq, expected",
|
130 |
+
[
|
131 |
+
("2018-01-01 00:02:06", "2s", "2018-01-01 00:02:06"),
|
132 |
+
("2018-01-01 00:02:00", "2min", "2018-01-01 00:02:00"),
|
133 |
+
("2018-01-01 00:04:00", "4min", "2018-01-01 00:04:00"),
|
134 |
+
("2018-01-01 00:15:00", "15min", "2018-01-01 00:15:00"),
|
135 |
+
("2018-01-01 00:20:00", "20min", "2018-01-01 00:20:00"),
|
136 |
+
("2018-01-01 03:00:00", "3h", "2018-01-01 03:00:00"),
|
137 |
+
],
|
138 |
+
)
|
139 |
+
@pytest.mark.parametrize("rounder", ["ceil", "floor", "round"])
|
140 |
+
def test_round_minute_freq(self, test_input, freq, expected, rounder):
|
141 |
+
# Ensure timestamps that shouldn't round dont!
|
142 |
+
# GH#21262
|
143 |
+
|
144 |
+
dt = Timestamp(test_input)
|
145 |
+
expected = Timestamp(expected)
|
146 |
+
func = getattr(dt, rounder)
|
147 |
+
result = func(freq)
|
148 |
+
assert result == expected
|
149 |
+
|
150 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
151 |
+
def test_ceil(self, unit):
|
152 |
+
dt = Timestamp("20130101 09:10:11").as_unit(unit)
|
153 |
+
result = dt.ceil("D")
|
154 |
+
expected = Timestamp("20130102")
|
155 |
+
assert result == expected
|
156 |
+
assert result._creso == dt._creso
|
157 |
+
|
158 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
159 |
+
def test_floor(self, unit):
|
160 |
+
dt = Timestamp("20130101 09:10:11").as_unit(unit)
|
161 |
+
result = dt.floor("D")
|
162 |
+
expected = Timestamp("20130101")
|
163 |
+
assert result == expected
|
164 |
+
assert result._creso == dt._creso
|
165 |
+
|
166 |
+
@pytest.mark.parametrize("method", ["ceil", "round", "floor"])
|
167 |
+
@pytest.mark.parametrize(
|
168 |
+
"unit",
|
169 |
+
["ns", "us", "ms", "s"],
|
170 |
+
)
|
171 |
+
def test_round_dst_border_ambiguous(self, method, unit):
|
172 |
+
# GH 18946 round near "fall back" DST
|
173 |
+
ts = Timestamp("2017-10-29 00:00:00", tz="UTC").tz_convert("Europe/Madrid")
|
174 |
+
ts = ts.as_unit(unit)
|
175 |
+
#
|
176 |
+
result = getattr(ts, method)("h", ambiguous=True)
|
177 |
+
assert result == ts
|
178 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
179 |
+
|
180 |
+
result = getattr(ts, method)("h", ambiguous=False)
|
181 |
+
expected = Timestamp("2017-10-29 01:00:00", tz="UTC").tz_convert(
|
182 |
+
"Europe/Madrid"
|
183 |
+
)
|
184 |
+
assert result == expected
|
185 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
186 |
+
|
187 |
+
result = getattr(ts, method)("h", ambiguous="NaT")
|
188 |
+
assert result is NaT
|
189 |
+
|
190 |
+
msg = "Cannot infer dst time"
|
191 |
+
with pytest.raises(pytz.AmbiguousTimeError, match=msg):
|
192 |
+
getattr(ts, method)("h", ambiguous="raise")
|
193 |
+
|
194 |
+
@pytest.mark.parametrize(
|
195 |
+
"method, ts_str, freq",
|
196 |
+
[
|
197 |
+
["ceil", "2018-03-11 01:59:00-0600", "5min"],
|
198 |
+
["round", "2018-03-11 01:59:00-0600", "5min"],
|
199 |
+
["floor", "2018-03-11 03:01:00-0500", "2h"],
|
200 |
+
],
|
201 |
+
)
|
202 |
+
@pytest.mark.parametrize(
|
203 |
+
"unit",
|
204 |
+
["ns", "us", "ms", "s"],
|
205 |
+
)
|
206 |
+
def test_round_dst_border_nonexistent(self, method, ts_str, freq, unit):
|
207 |
+
# GH 23324 round near "spring forward" DST
|
208 |
+
ts = Timestamp(ts_str, tz="America/Chicago").as_unit(unit)
|
209 |
+
result = getattr(ts, method)(freq, nonexistent="shift_forward")
|
210 |
+
expected = Timestamp("2018-03-11 03:00:00", tz="America/Chicago")
|
211 |
+
assert result == expected
|
212 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
213 |
+
|
214 |
+
result = getattr(ts, method)(freq, nonexistent="NaT")
|
215 |
+
assert result is NaT
|
216 |
+
|
217 |
+
msg = "2018-03-11 02:00:00"
|
218 |
+
with pytest.raises(pytz.NonExistentTimeError, match=msg):
|
219 |
+
getattr(ts, method)(freq, nonexistent="raise")
|
220 |
+
|
221 |
+
@pytest.mark.parametrize(
|
222 |
+
"timestamp",
|
223 |
+
[
|
224 |
+
"2018-01-01 0:0:0.124999360",
|
225 |
+
"2018-01-01 0:0:0.125000367",
|
226 |
+
"2018-01-01 0:0:0.125500",
|
227 |
+
"2018-01-01 0:0:0.126500",
|
228 |
+
"2018-01-01 12:00:00",
|
229 |
+
"2019-01-01 12:00:00",
|
230 |
+
],
|
231 |
+
)
|
232 |
+
@pytest.mark.parametrize(
|
233 |
+
"freq",
|
234 |
+
[
|
235 |
+
"2ns",
|
236 |
+
"3ns",
|
237 |
+
"4ns",
|
238 |
+
"5ns",
|
239 |
+
"6ns",
|
240 |
+
"7ns",
|
241 |
+
"250ns",
|
242 |
+
"500ns",
|
243 |
+
"750ns",
|
244 |
+
"1us",
|
245 |
+
"19us",
|
246 |
+
"250us",
|
247 |
+
"500us",
|
248 |
+
"750us",
|
249 |
+
"1s",
|
250 |
+
"2s",
|
251 |
+
"3s",
|
252 |
+
"1D",
|
253 |
+
],
|
254 |
+
)
|
255 |
+
def test_round_int64(self, timestamp, freq):
|
256 |
+
# check that all rounding modes are accurate to int64 precision
|
257 |
+
# see GH#22591
|
258 |
+
dt = Timestamp(timestamp).as_unit("ns")
|
259 |
+
unit = to_offset(freq).nanos
|
260 |
+
|
261 |
+
# test floor
|
262 |
+
result = dt.floor(freq)
|
263 |
+
assert result._value % unit == 0, f"floor not a {freq} multiple"
|
264 |
+
assert 0 <= dt._value - result._value < unit, "floor error"
|
265 |
+
|
266 |
+
# test ceil
|
267 |
+
result = dt.ceil(freq)
|
268 |
+
assert result._value % unit == 0, f"ceil not a {freq} multiple"
|
269 |
+
assert 0 <= result._value - dt._value < unit, "ceil error"
|
270 |
+
|
271 |
+
# test round
|
272 |
+
result = dt.round(freq)
|
273 |
+
assert result._value % unit == 0, f"round not a {freq} multiple"
|
274 |
+
assert abs(result._value - dt._value) <= unit // 2, "round error"
|
275 |
+
if unit % 2 == 0 and abs(result._value - dt._value) == unit // 2:
|
276 |
+
# round half to even
|
277 |
+
assert result._value // unit % 2 == 0, "round half to even error"
|
278 |
+
|
279 |
+
def test_round_implementation_bounds(self):
|
280 |
+
# See also: analogous test for Timedelta
|
281 |
+
result = Timestamp.min.ceil("s")
|
282 |
+
expected = Timestamp(1677, 9, 21, 0, 12, 44)
|
283 |
+
assert result == expected
|
284 |
+
|
285 |
+
result = Timestamp.max.floor("s")
|
286 |
+
expected = Timestamp.max - Timedelta(854775807)
|
287 |
+
assert result == expected
|
288 |
+
|
289 |
+
msg = "Cannot round 1677-09-21 00:12:43.145224193 to freq=<Second>"
|
290 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
291 |
+
Timestamp.min.floor("s")
|
292 |
+
|
293 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
294 |
+
Timestamp.min.round("s")
|
295 |
+
|
296 |
+
msg = "Cannot round 2262-04-11 23:47:16.854775807 to freq=<Second>"
|
297 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
298 |
+
Timestamp.max.ceil("s")
|
299 |
+
|
300 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
301 |
+
Timestamp.max.round("s")
|
302 |
+
|
303 |
+
@given(val=st.integers(iNaT + 1, lib.i8max))
|
304 |
+
@pytest.mark.parametrize(
|
305 |
+
"method", [Timestamp.round, Timestamp.floor, Timestamp.ceil]
|
306 |
+
)
|
307 |
+
def test_round_sanity(self, val, method):
|
308 |
+
cls = Timestamp
|
309 |
+
err_cls = OutOfBoundsDatetime
|
310 |
+
|
311 |
+
val = np.int64(val)
|
312 |
+
ts = cls(val)
|
313 |
+
|
314 |
+
def checker(ts, nanos, unit):
|
315 |
+
# First check that we do raise in cases where we should
|
316 |
+
if nanos == 1:
|
317 |
+
pass
|
318 |
+
else:
|
319 |
+
div, mod = divmod(ts._value, nanos)
|
320 |
+
diff = int(nanos - mod)
|
321 |
+
lb = ts._value - mod
|
322 |
+
assert lb <= ts._value # i.e. no overflows with python ints
|
323 |
+
ub = ts._value + diff
|
324 |
+
assert ub > ts._value # i.e. no overflows with python ints
|
325 |
+
|
326 |
+
msg = "without overflow"
|
327 |
+
if mod == 0:
|
328 |
+
# We should never be raising in this
|
329 |
+
pass
|
330 |
+
elif method is cls.ceil:
|
331 |
+
if ub > cls.max._value:
|
332 |
+
with pytest.raises(err_cls, match=msg):
|
333 |
+
method(ts, unit)
|
334 |
+
return
|
335 |
+
elif method is cls.floor:
|
336 |
+
if lb < cls.min._value:
|
337 |
+
with pytest.raises(err_cls, match=msg):
|
338 |
+
method(ts, unit)
|
339 |
+
return
|
340 |
+
elif mod >= diff:
|
341 |
+
if ub > cls.max._value:
|
342 |
+
with pytest.raises(err_cls, match=msg):
|
343 |
+
method(ts, unit)
|
344 |
+
return
|
345 |
+
elif lb < cls.min._value:
|
346 |
+
with pytest.raises(err_cls, match=msg):
|
347 |
+
method(ts, unit)
|
348 |
+
return
|
349 |
+
|
350 |
+
res = method(ts, unit)
|
351 |
+
|
352 |
+
td = res - ts
|
353 |
+
diff = abs(td._value)
|
354 |
+
assert diff < nanos
|
355 |
+
assert res._value % nanos == 0
|
356 |
+
|
357 |
+
if method is cls.round:
|
358 |
+
assert diff <= nanos / 2
|
359 |
+
elif method is cls.floor:
|
360 |
+
assert res <= ts
|
361 |
+
elif method is cls.ceil:
|
362 |
+
assert res >= ts
|
363 |
+
|
364 |
+
nanos = 1
|
365 |
+
checker(ts, nanos, "ns")
|
366 |
+
|
367 |
+
nanos = 1000
|
368 |
+
checker(ts, nanos, "us")
|
369 |
+
|
370 |
+
nanos = 1_000_000
|
371 |
+
checker(ts, nanos, "ms")
|
372 |
+
|
373 |
+
nanos = 1_000_000_000
|
374 |
+
checker(ts, nanos, "s")
|
375 |
+
|
376 |
+
nanos = 60 * 1_000_000_000
|
377 |
+
checker(ts, nanos, "min")
|
378 |
+
|
379 |
+
nanos = 60 * 60 * 1_000_000_000
|
380 |
+
checker(ts, nanos, "h")
|
381 |
+
|
382 |
+
nanos = 24 * 60 * 60 * 1_000_000_000
|
383 |
+
checker(ts, nanos, "D")
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_timestamp_method.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# NB: This is for the Timestamp.timestamp *method* specifically, not
|
2 |
+
# the Timestamp class in general.
|
3 |
+
|
4 |
+
from pytz import utc
|
5 |
+
|
6 |
+
from pandas._libs.tslibs import Timestamp
|
7 |
+
import pandas.util._test_decorators as td
|
8 |
+
|
9 |
+
import pandas._testing as tm
|
10 |
+
|
11 |
+
|
12 |
+
class TestTimestampMethod:
|
13 |
+
@td.skip_if_windows
|
14 |
+
def test_timestamp(self, fixed_now_ts):
|
15 |
+
# GH#17329
|
16 |
+
# tz-naive --> treat it as if it were UTC for purposes of timestamp()
|
17 |
+
ts = fixed_now_ts
|
18 |
+
uts = ts.replace(tzinfo=utc)
|
19 |
+
assert ts.timestamp() == uts.timestamp()
|
20 |
+
|
21 |
+
tsc = Timestamp("2014-10-11 11:00:01.12345678", tz="US/Central")
|
22 |
+
utsc = tsc.tz_convert("UTC")
|
23 |
+
|
24 |
+
# utsc is a different representation of the same time
|
25 |
+
assert tsc.timestamp() == utsc.timestamp()
|
26 |
+
|
27 |
+
# datetime.timestamp() converts in the local timezone
|
28 |
+
with tm.set_timezone("UTC"):
|
29 |
+
# should agree with datetime.timestamp method
|
30 |
+
dt = ts.to_pydatetime()
|
31 |
+
assert dt.timestamp() == ts.timestamp()
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_to_julian_date.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pandas import Timestamp
|
2 |
+
|
3 |
+
|
4 |
+
class TestTimestampToJulianDate:
|
5 |
+
def test_compare_1700(self):
|
6 |
+
ts = Timestamp("1700-06-23")
|
7 |
+
res = ts.to_julian_date()
|
8 |
+
assert res == 2_342_145.5
|
9 |
+
|
10 |
+
def test_compare_2000(self):
|
11 |
+
ts = Timestamp("2000-04-12")
|
12 |
+
res = ts.to_julian_date()
|
13 |
+
assert res == 2_451_646.5
|
14 |
+
|
15 |
+
def test_compare_2100(self):
|
16 |
+
ts = Timestamp("2100-08-12")
|
17 |
+
res = ts.to_julian_date()
|
18 |
+
assert res == 2_488_292.5
|
19 |
+
|
20 |
+
def test_compare_hour01(self):
|
21 |
+
ts = Timestamp("2000-08-12T01:00:00")
|
22 |
+
res = ts.to_julian_date()
|
23 |
+
assert res == 2_451_768.5416666666666666
|
24 |
+
|
25 |
+
def test_compare_hour13(self):
|
26 |
+
ts = Timestamp("2000-08-12T13:00:00")
|
27 |
+
res = ts.to_julian_date()
|
28 |
+
assert res == 2_451_769.0416666666666666
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_to_pydatetime.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import (
|
2 |
+
datetime,
|
3 |
+
timedelta,
|
4 |
+
)
|
5 |
+
|
6 |
+
import pytz
|
7 |
+
|
8 |
+
from pandas._libs.tslibs.timezones import dateutil_gettz as gettz
|
9 |
+
import pandas.util._test_decorators as td
|
10 |
+
|
11 |
+
from pandas import Timestamp
|
12 |
+
import pandas._testing as tm
|
13 |
+
|
14 |
+
|
15 |
+
class TestTimestampToPyDatetime:
|
16 |
+
def test_to_pydatetime_fold(self):
|
17 |
+
# GH#45087
|
18 |
+
tzstr = "dateutil/usr/share/zoneinfo/America/Chicago"
|
19 |
+
ts = Timestamp(year=2013, month=11, day=3, hour=1, minute=0, fold=1, tz=tzstr)
|
20 |
+
dt = ts.to_pydatetime()
|
21 |
+
assert dt.fold == 1
|
22 |
+
|
23 |
+
def test_to_pydatetime_nonzero_nano(self):
|
24 |
+
ts = Timestamp("2011-01-01 9:00:00.123456789")
|
25 |
+
|
26 |
+
# Warn the user of data loss (nanoseconds).
|
27 |
+
with tm.assert_produces_warning(UserWarning):
|
28 |
+
expected = datetime(2011, 1, 1, 9, 0, 0, 123456)
|
29 |
+
result = ts.to_pydatetime()
|
30 |
+
assert result == expected
|
31 |
+
|
32 |
+
def test_timestamp_to_datetime(self):
|
33 |
+
stamp = Timestamp("20090415", tz="US/Eastern")
|
34 |
+
dtval = stamp.to_pydatetime()
|
35 |
+
assert stamp == dtval
|
36 |
+
assert stamp.tzinfo == dtval.tzinfo
|
37 |
+
|
38 |
+
def test_timestamp_to_pydatetime_dateutil(self):
|
39 |
+
stamp = Timestamp("20090415", tz="dateutil/US/Eastern")
|
40 |
+
dtval = stamp.to_pydatetime()
|
41 |
+
assert stamp == dtval
|
42 |
+
assert stamp.tzinfo == dtval.tzinfo
|
43 |
+
|
44 |
+
def test_timestamp_to_pydatetime_explicit_pytz(self):
|
45 |
+
stamp = Timestamp("20090415", tz=pytz.timezone("US/Eastern"))
|
46 |
+
dtval = stamp.to_pydatetime()
|
47 |
+
assert stamp == dtval
|
48 |
+
assert stamp.tzinfo == dtval.tzinfo
|
49 |
+
|
50 |
+
@td.skip_if_windows
|
51 |
+
def test_timestamp_to_pydatetime_explicit_dateutil(self):
|
52 |
+
stamp = Timestamp("20090415", tz=gettz("US/Eastern"))
|
53 |
+
dtval = stamp.to_pydatetime()
|
54 |
+
assert stamp == dtval
|
55 |
+
assert stamp.tzinfo == dtval.tzinfo
|
56 |
+
|
57 |
+
def test_to_pydatetime_bijective(self):
|
58 |
+
# Ensure that converting to datetime and back only loses precision
|
59 |
+
# by going from nanoseconds to microseconds.
|
60 |
+
exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning
|
61 |
+
with tm.assert_produces_warning(exp_warning):
|
62 |
+
pydt_max = Timestamp.max.to_pydatetime()
|
63 |
+
|
64 |
+
assert (
|
65 |
+
Timestamp(pydt_max).as_unit("ns")._value / 1000
|
66 |
+
== Timestamp.max._value / 1000
|
67 |
+
)
|
68 |
+
|
69 |
+
exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning
|
70 |
+
with tm.assert_produces_warning(exp_warning):
|
71 |
+
pydt_min = Timestamp.min.to_pydatetime()
|
72 |
+
|
73 |
+
# The next assertion can be enabled once GH#39221 is merged
|
74 |
+
# assert pydt_min < Timestamp.min # this is bc nanos are dropped
|
75 |
+
tdus = timedelta(microseconds=1)
|
76 |
+
assert pydt_min + tdus > Timestamp.min
|
77 |
+
|
78 |
+
assert (
|
79 |
+
Timestamp(pydt_min + tdus).as_unit("ns")._value / 1000
|
80 |
+
== Timestamp.min._value / 1000
|
81 |
+
)
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_tz_convert.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dateutil
|
2 |
+
import pytest
|
3 |
+
|
4 |
+
from pandas._libs.tslibs import timezones
|
5 |
+
import pandas.util._test_decorators as td
|
6 |
+
|
7 |
+
from pandas import Timestamp
|
8 |
+
|
9 |
+
|
10 |
+
class TestTimestampTZConvert:
|
11 |
+
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
|
12 |
+
def test_astimezone(self, tzstr):
|
13 |
+
# astimezone is an alias for tz_convert, so keep it with
|
14 |
+
# the tz_convert tests
|
15 |
+
utcdate = Timestamp("3/11/2012 22:00", tz="UTC")
|
16 |
+
expected = utcdate.tz_convert(tzstr)
|
17 |
+
result = utcdate.astimezone(tzstr)
|
18 |
+
assert expected == result
|
19 |
+
assert isinstance(result, Timestamp)
|
20 |
+
|
21 |
+
@pytest.mark.parametrize(
|
22 |
+
"stamp",
|
23 |
+
[
|
24 |
+
"2014-02-01 09:00",
|
25 |
+
"2014-07-08 09:00",
|
26 |
+
"2014-11-01 17:00",
|
27 |
+
"2014-11-05 00:00",
|
28 |
+
],
|
29 |
+
)
|
30 |
+
def test_tz_convert_roundtrip(self, stamp, tz_aware_fixture):
|
31 |
+
tz = tz_aware_fixture
|
32 |
+
|
33 |
+
ts = Timestamp(stamp, tz="UTC")
|
34 |
+
converted = ts.tz_convert(tz)
|
35 |
+
|
36 |
+
reset = converted.tz_convert(None)
|
37 |
+
assert reset == Timestamp(stamp)
|
38 |
+
assert reset.tzinfo is None
|
39 |
+
assert reset == converted.tz_convert("UTC").tz_localize(None)
|
40 |
+
|
41 |
+
@td.skip_if_windows
|
42 |
+
def test_tz_convert_utc_with_system_utc(self):
|
43 |
+
# from system utc to real utc
|
44 |
+
ts = Timestamp("2001-01-05 11:56", tz=timezones.maybe_get_tz("dateutil/UTC"))
|
45 |
+
# check that the time hasn't changed.
|
46 |
+
assert ts == ts.tz_convert(dateutil.tz.tzutc())
|
47 |
+
|
48 |
+
# from system utc to real utc
|
49 |
+
ts = Timestamp("2001-01-05 11:56", tz=timezones.maybe_get_tz("dateutil/UTC"))
|
50 |
+
# check that the time hasn't changed.
|
51 |
+
assert ts == ts.tz_convert(dateutil.tz.tzutc())
|
llmeval-env/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_tz_localize.py
ADDED
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import timedelta
|
2 |
+
import re
|
3 |
+
|
4 |
+
from dateutil.tz import gettz
|
5 |
+
import pytest
|
6 |
+
import pytz
|
7 |
+
from pytz.exceptions import (
|
8 |
+
AmbiguousTimeError,
|
9 |
+
NonExistentTimeError,
|
10 |
+
)
|
11 |
+
|
12 |
+
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
|
13 |
+
from pandas.errors import OutOfBoundsDatetime
|
14 |
+
|
15 |
+
from pandas import (
|
16 |
+
NaT,
|
17 |
+
Timestamp,
|
18 |
+
)
|
19 |
+
|
20 |
+
try:
|
21 |
+
from zoneinfo import ZoneInfo
|
22 |
+
except ImportError:
|
23 |
+
# Cannot assign to a type
|
24 |
+
ZoneInfo = None # type: ignore[misc, assignment]
|
25 |
+
|
26 |
+
|
27 |
+
class TestTimestampTZLocalize:
|
28 |
+
@pytest.mark.skip_ubsan
|
29 |
+
def test_tz_localize_pushes_out_of_bounds(self):
|
30 |
+
# GH#12677
|
31 |
+
# tz_localize that pushes away from the boundary is OK
|
32 |
+
msg = (
|
33 |
+
f"Converting {Timestamp.min.strftime('%Y-%m-%d %H:%M:%S')} "
|
34 |
+
f"underflows past {Timestamp.min}"
|
35 |
+
)
|
36 |
+
pac = Timestamp.min.tz_localize("US/Pacific")
|
37 |
+
assert pac._value > Timestamp.min._value
|
38 |
+
pac.tz_convert("Asia/Tokyo") # tz_convert doesn't change value
|
39 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
40 |
+
Timestamp.min.tz_localize("Asia/Tokyo")
|
41 |
+
|
42 |
+
# tz_localize that pushes away from the boundary is OK
|
43 |
+
msg = (
|
44 |
+
f"Converting {Timestamp.max.strftime('%Y-%m-%d %H:%M:%S')} "
|
45 |
+
f"overflows past {Timestamp.max}"
|
46 |
+
)
|
47 |
+
tokyo = Timestamp.max.tz_localize("Asia/Tokyo")
|
48 |
+
assert tokyo._value < Timestamp.max._value
|
49 |
+
tokyo.tz_convert("US/Pacific") # tz_convert doesn't change value
|
50 |
+
with pytest.raises(OutOfBoundsDatetime, match=msg):
|
51 |
+
Timestamp.max.tz_localize("US/Pacific")
|
52 |
+
|
53 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
54 |
+
def test_tz_localize_ambiguous_bool(self, unit):
|
55 |
+
# make sure that we are correctly accepting bool values as ambiguous
|
56 |
+
# GH#14402
|
57 |
+
ts = Timestamp("2015-11-01 01:00:03").as_unit(unit)
|
58 |
+
expected0 = Timestamp("2015-11-01 01:00:03-0500", tz="US/Central")
|
59 |
+
expected1 = Timestamp("2015-11-01 01:00:03-0600", tz="US/Central")
|
60 |
+
|
61 |
+
msg = "Cannot infer dst time from 2015-11-01 01:00:03"
|
62 |
+
with pytest.raises(pytz.AmbiguousTimeError, match=msg):
|
63 |
+
ts.tz_localize("US/Central")
|
64 |
+
|
65 |
+
with pytest.raises(pytz.AmbiguousTimeError, match=msg):
|
66 |
+
ts.tz_localize("dateutil/US/Central")
|
67 |
+
|
68 |
+
if ZoneInfo is not None:
|
69 |
+
try:
|
70 |
+
tz = ZoneInfo("US/Central")
|
71 |
+
except KeyError:
|
72 |
+
# no tzdata
|
73 |
+
pass
|
74 |
+
else:
|
75 |
+
with pytest.raises(pytz.AmbiguousTimeError, match=msg):
|
76 |
+
ts.tz_localize(tz)
|
77 |
+
|
78 |
+
result = ts.tz_localize("US/Central", ambiguous=True)
|
79 |
+
assert result == expected0
|
80 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
81 |
+
|
82 |
+
result = ts.tz_localize("US/Central", ambiguous=False)
|
83 |
+
assert result == expected1
|
84 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
85 |
+
|
86 |
+
def test_tz_localize_ambiguous(self):
|
87 |
+
ts = Timestamp("2014-11-02 01:00")
|
88 |
+
ts_dst = ts.tz_localize("US/Eastern", ambiguous=True)
|
89 |
+
ts_no_dst = ts.tz_localize("US/Eastern", ambiguous=False)
|
90 |
+
|
91 |
+
assert ts_no_dst._value - ts_dst._value == 3600
|
92 |
+
msg = re.escape(
|
93 |
+
"'ambiguous' parameter must be one of: "
|
94 |
+
"True, False, 'NaT', 'raise' (default)"
|
95 |
+
)
|
96 |
+
with pytest.raises(ValueError, match=msg):
|
97 |
+
ts.tz_localize("US/Eastern", ambiguous="infer")
|
98 |
+
|
99 |
+
# GH#8025
|
100 |
+
msg = "Cannot localize tz-aware Timestamp, use tz_convert for conversions"
|
101 |
+
with pytest.raises(TypeError, match=msg):
|
102 |
+
Timestamp("2011-01-01", tz="US/Eastern").tz_localize("Asia/Tokyo")
|
103 |
+
|
104 |
+
msg = "Cannot convert tz-naive Timestamp, use tz_localize to localize"
|
105 |
+
with pytest.raises(TypeError, match=msg):
|
106 |
+
Timestamp("2011-01-01").tz_convert("Asia/Tokyo")
|
107 |
+
|
108 |
+
@pytest.mark.parametrize(
|
109 |
+
"stamp, tz",
|
110 |
+
[
|
111 |
+
("2015-03-08 02:00", "US/Eastern"),
|
112 |
+
("2015-03-08 02:30", "US/Pacific"),
|
113 |
+
("2015-03-29 02:00", "Europe/Paris"),
|
114 |
+
("2015-03-29 02:30", "Europe/Belgrade"),
|
115 |
+
],
|
116 |
+
)
|
117 |
+
def test_tz_localize_nonexistent(self, stamp, tz):
|
118 |
+
# GH#13057
|
119 |
+
ts = Timestamp(stamp)
|
120 |
+
with pytest.raises(NonExistentTimeError, match=stamp):
|
121 |
+
ts.tz_localize(tz)
|
122 |
+
# GH 22644
|
123 |
+
with pytest.raises(NonExistentTimeError, match=stamp):
|
124 |
+
ts.tz_localize(tz, nonexistent="raise")
|
125 |
+
assert ts.tz_localize(tz, nonexistent="NaT") is NaT
|
126 |
+
|
127 |
+
@pytest.mark.parametrize(
|
128 |
+
"stamp, tz, forward_expected, backward_expected",
|
129 |
+
[
|
130 |
+
(
|
131 |
+
"2015-03-29 02:00:00",
|
132 |
+
"Europe/Warsaw",
|
133 |
+
"2015-03-29 03:00:00",
|
134 |
+
"2015-03-29 01:59:59",
|
135 |
+
), # utc+1 -> utc+2
|
136 |
+
(
|
137 |
+
"2023-03-12 02:00:00",
|
138 |
+
"America/Los_Angeles",
|
139 |
+
"2023-03-12 03:00:00",
|
140 |
+
"2023-03-12 01:59:59",
|
141 |
+
), # utc-8 -> utc-7
|
142 |
+
(
|
143 |
+
"2023-03-26 01:00:00",
|
144 |
+
"Europe/London",
|
145 |
+
"2023-03-26 02:00:00",
|
146 |
+
"2023-03-26 00:59:59",
|
147 |
+
), # utc+0 -> utc+1
|
148 |
+
(
|
149 |
+
"2023-03-26 00:00:00",
|
150 |
+
"Atlantic/Azores",
|
151 |
+
"2023-03-26 01:00:00",
|
152 |
+
"2023-03-25 23:59:59",
|
153 |
+
), # utc-1 -> utc+0
|
154 |
+
],
|
155 |
+
)
|
156 |
+
def test_tz_localize_nonexistent_shift(
|
157 |
+
self, stamp, tz, forward_expected, backward_expected
|
158 |
+
):
|
159 |
+
ts = Timestamp(stamp)
|
160 |
+
forward_ts = ts.tz_localize(tz, nonexistent="shift_forward")
|
161 |
+
assert forward_ts == Timestamp(forward_expected, tz=tz)
|
162 |
+
backward_ts = ts.tz_localize(tz, nonexistent="shift_backward")
|
163 |
+
assert backward_ts == Timestamp(backward_expected, tz=tz)
|
164 |
+
|
165 |
+
def test_tz_localize_ambiguous_raise(self):
|
166 |
+
# GH#13057
|
167 |
+
ts = Timestamp("2015-11-1 01:00")
|
168 |
+
msg = "Cannot infer dst time from 2015-11-01 01:00:00,"
|
169 |
+
with pytest.raises(AmbiguousTimeError, match=msg):
|
170 |
+
ts.tz_localize("US/Pacific", ambiguous="raise")
|
171 |
+
|
172 |
+
def test_tz_localize_nonexistent_invalid_arg(self, warsaw):
|
173 |
+
# GH 22644
|
174 |
+
tz = warsaw
|
175 |
+
ts = Timestamp("2015-03-29 02:00:00")
|
176 |
+
msg = (
|
177 |
+
"The nonexistent argument must be one of 'raise', 'NaT', "
|
178 |
+
"'shift_forward', 'shift_backward' or a timedelta object"
|
179 |
+
)
|
180 |
+
with pytest.raises(ValueError, match=msg):
|
181 |
+
ts.tz_localize(tz, nonexistent="foo")
|
182 |
+
|
183 |
+
@pytest.mark.parametrize(
|
184 |
+
"stamp",
|
185 |
+
[
|
186 |
+
"2014-02-01 09:00",
|
187 |
+
"2014-07-08 09:00",
|
188 |
+
"2014-11-01 17:00",
|
189 |
+
"2014-11-05 00:00",
|
190 |
+
],
|
191 |
+
)
|
192 |
+
def test_tz_localize_roundtrip(self, stamp, tz_aware_fixture):
|
193 |
+
tz = tz_aware_fixture
|
194 |
+
ts = Timestamp(stamp)
|
195 |
+
localized = ts.tz_localize(tz)
|
196 |
+
assert localized == Timestamp(stamp, tz=tz)
|
197 |
+
|
198 |
+
msg = "Cannot localize tz-aware Timestamp"
|
199 |
+
with pytest.raises(TypeError, match=msg):
|
200 |
+
localized.tz_localize(tz)
|
201 |
+
|
202 |
+
reset = localized.tz_localize(None)
|
203 |
+
assert reset == ts
|
204 |
+
assert reset.tzinfo is None
|
205 |
+
|
206 |
+
def test_tz_localize_ambiguous_compat(self):
|
207 |
+
# validate that pytz and dateutil are compat for dst
|
208 |
+
# when the transition happens
|
209 |
+
naive = Timestamp("2013-10-27 01:00:00")
|
210 |
+
|
211 |
+
pytz_zone = "Europe/London"
|
212 |
+
dateutil_zone = "dateutil/Europe/London"
|
213 |
+
result_pytz = naive.tz_localize(pytz_zone, ambiguous=False)
|
214 |
+
result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=False)
|
215 |
+
assert result_pytz._value == result_dateutil._value
|
216 |
+
assert result_pytz._value == 1382835600
|
217 |
+
|
218 |
+
# fixed ambiguous behavior
|
219 |
+
# see gh-14621, GH#45087
|
220 |
+
assert result_pytz.to_pydatetime().tzname() == "GMT"
|
221 |
+
assert result_dateutil.to_pydatetime().tzname() == "GMT"
|
222 |
+
assert str(result_pytz) == str(result_dateutil)
|
223 |
+
|
224 |
+
# 1 hour difference
|
225 |
+
result_pytz = naive.tz_localize(pytz_zone, ambiguous=True)
|
226 |
+
result_dateutil = naive.tz_localize(dateutil_zone, ambiguous=True)
|
227 |
+
assert result_pytz._value == result_dateutil._value
|
228 |
+
assert result_pytz._value == 1382832000
|
229 |
+
|
230 |
+
# see gh-14621
|
231 |
+
assert str(result_pytz) == str(result_dateutil)
|
232 |
+
assert (
|
233 |
+
result_pytz.to_pydatetime().tzname()
|
234 |
+
== result_dateutil.to_pydatetime().tzname()
|
235 |
+
)
|
236 |
+
|
237 |
+
@pytest.mark.parametrize(
|
238 |
+
"tz",
|
239 |
+
[
|
240 |
+
pytz.timezone("US/Eastern"),
|
241 |
+
gettz("US/Eastern"),
|
242 |
+
"US/Eastern",
|
243 |
+
"dateutil/US/Eastern",
|
244 |
+
],
|
245 |
+
)
|
246 |
+
def test_timestamp_tz_localize(self, tz):
|
247 |
+
stamp = Timestamp("3/11/2012 04:00")
|
248 |
+
|
249 |
+
result = stamp.tz_localize(tz)
|
250 |
+
expected = Timestamp("3/11/2012 04:00", tz=tz)
|
251 |
+
assert result.hour == expected.hour
|
252 |
+
assert result == expected
|
253 |
+
|
254 |
+
@pytest.mark.parametrize(
|
255 |
+
"start_ts, tz, end_ts, shift",
|
256 |
+
[
|
257 |
+
["2015-03-29 02:20:00", "Europe/Warsaw", "2015-03-29 03:00:00", "forward"],
|
258 |
+
[
|
259 |
+
"2015-03-29 02:20:00",
|
260 |
+
"Europe/Warsaw",
|
261 |
+
"2015-03-29 01:59:59.999999999",
|
262 |
+
"backward",
|
263 |
+
],
|
264 |
+
[
|
265 |
+
"2015-03-29 02:20:00",
|
266 |
+
"Europe/Warsaw",
|
267 |
+
"2015-03-29 03:20:00",
|
268 |
+
timedelta(hours=1),
|
269 |
+
],
|
270 |
+
[
|
271 |
+
"2015-03-29 02:20:00",
|
272 |
+
"Europe/Warsaw",
|
273 |
+
"2015-03-29 01:20:00",
|
274 |
+
timedelta(hours=-1),
|
275 |
+
],
|
276 |
+
["2018-03-11 02:33:00", "US/Pacific", "2018-03-11 03:00:00", "forward"],
|
277 |
+
[
|
278 |
+
"2018-03-11 02:33:00",
|
279 |
+
"US/Pacific",
|
280 |
+
"2018-03-11 01:59:59.999999999",
|
281 |
+
"backward",
|
282 |
+
],
|
283 |
+
[
|
284 |
+
"2018-03-11 02:33:00",
|
285 |
+
"US/Pacific",
|
286 |
+
"2018-03-11 03:33:00",
|
287 |
+
timedelta(hours=1),
|
288 |
+
],
|
289 |
+
[
|
290 |
+
"2018-03-11 02:33:00",
|
291 |
+
"US/Pacific",
|
292 |
+
"2018-03-11 01:33:00",
|
293 |
+
timedelta(hours=-1),
|
294 |
+
],
|
295 |
+
],
|
296 |
+
)
|
297 |
+
@pytest.mark.parametrize("tz_type", ["", "dateutil/"])
|
298 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
299 |
+
def test_timestamp_tz_localize_nonexistent_shift(
|
300 |
+
self, start_ts, tz, end_ts, shift, tz_type, unit
|
301 |
+
):
|
302 |
+
# GH 8917, 24466
|
303 |
+
tz = tz_type + tz
|
304 |
+
if isinstance(shift, str):
|
305 |
+
shift = "shift_" + shift
|
306 |
+
ts = Timestamp(start_ts).as_unit(unit)
|
307 |
+
result = ts.tz_localize(tz, nonexistent=shift)
|
308 |
+
expected = Timestamp(end_ts).tz_localize(tz)
|
309 |
+
|
310 |
+
if unit == "us":
|
311 |
+
assert result == expected.replace(nanosecond=0)
|
312 |
+
elif unit == "ms":
|
313 |
+
micros = expected.microsecond - expected.microsecond % 1000
|
314 |
+
assert result == expected.replace(microsecond=micros, nanosecond=0)
|
315 |
+
elif unit == "s":
|
316 |
+
assert result == expected.replace(microsecond=0, nanosecond=0)
|
317 |
+
else:
|
318 |
+
assert result == expected
|
319 |
+
assert result._creso == getattr(NpyDatetimeUnit, f"NPY_FR_{unit}").value
|
320 |
+
|
321 |
+
@pytest.mark.parametrize("offset", [-1, 1])
|
322 |
+
def test_timestamp_tz_localize_nonexistent_shift_invalid(self, offset, warsaw):
|
323 |
+
# GH 8917, 24466
|
324 |
+
tz = warsaw
|
325 |
+
ts = Timestamp("2015-03-29 02:20:00")
|
326 |
+
msg = "The provided timedelta will relocalize on a nonexistent time"
|
327 |
+
with pytest.raises(ValueError, match=msg):
|
328 |
+
ts.tz_localize(tz, nonexistent=timedelta(seconds=offset))
|
329 |
+
|
330 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
331 |
+
def test_timestamp_tz_localize_nonexistent_NaT(self, warsaw, unit):
|
332 |
+
# GH 8917
|
333 |
+
tz = warsaw
|
334 |
+
ts = Timestamp("2015-03-29 02:20:00").as_unit(unit)
|
335 |
+
result = ts.tz_localize(tz, nonexistent="NaT")
|
336 |
+
assert result is NaT
|
337 |
+
|
338 |
+
@pytest.mark.parametrize("unit", ["ns", "us", "ms", "s"])
|
339 |
+
def test_timestamp_tz_localize_nonexistent_raise(self, warsaw, unit):
|
340 |
+
# GH 8917
|
341 |
+
tz = warsaw
|
342 |
+
ts = Timestamp("2015-03-29 02:20:00").as_unit(unit)
|
343 |
+
msg = "2015-03-29 02:20:00"
|
344 |
+
with pytest.raises(pytz.NonExistentTimeError, match=msg):
|
345 |
+
ts.tz_localize(tz, nonexistent="raise")
|
346 |
+
msg = (
|
347 |
+
"The nonexistent argument must be one of 'raise', 'NaT', "
|
348 |
+
"'shift_forward', 'shift_backward' or a timedelta object"
|
349 |
+
)
|
350 |
+
with pytest.raises(ValueError, match=msg):
|
351 |
+
ts.tz_localize(tz, nonexistent="foo")
|