applied-ai-018 commited on
Commit
ffeb68c
·
verified ·
1 Parent(s): b0b566c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/pandas/api/__init__.py +16 -0
  2. env-llmeval/lib/python3.10/site-packages/pandas/api/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/pandas/api/extensions/__init__.py +33 -0
  4. env-llmeval/lib/python3.10/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/pandas/api/indexers/__init__.py +17 -0
  6. env-llmeval/lib/python3.10/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/pandas/api/interchange/__init__.py +8 -0
  8. env-llmeval/lib/python3.10/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/pandas/api/types/__init__.py +23 -0
  10. env-llmeval/lib/python3.10/site-packages/pandas/api/types/__pycache__/__init__.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/pandas/api/typing/__init__.py +55 -0
  12. env-llmeval/lib/python3.10/site-packages/pandas/api/typing/__pycache__/__init__.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/__init__.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_util.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/pandas/tests/__init__.py +0 -0
  19. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/__init__.py +0 -0
  20. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/__init__.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_constructors.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_contains.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_formats.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_interval.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_overlaps.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/period/__init__.py +0 -0
  28. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/period/test_arithmetic.py +486 -0
  29. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/period/test_period.py +1154 -0
  30. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/test_na_scalar.py +316 -0
  31. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/test_nat.py +709 -0
  32. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__init__.py +0 -0
  33. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_arithmetic.py +1182 -0
  35. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_constructors.py +698 -0
  36. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_formats.py +109 -0
  37. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/test_timedelta.py +666 -0
  38. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__init__.py +0 -0
  39. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_as_unit.py +86 -0
  44. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_normalize.py +22 -0
  45. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/methods/test_tz_convert.py +51 -0
  46. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_arithmetic.py +334 -0
  47. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_comparisons.py +313 -0
  48. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_constructors.py +1068 -0
  49. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_formats.py +201 -0
  50. env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_timestamp.py +928 -0
env-llmeval/lib/python3.10/site-packages/pandas/api/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ public toolkit API """
2
+ from pandas.api import (
3
+ extensions,
4
+ indexers,
5
+ interchange,
6
+ types,
7
+ typing,
8
+ )
9
+
10
+ __all__ = [
11
+ "interchange",
12
+ "extensions",
13
+ "indexers",
14
+ "types",
15
+ "typing",
16
+ ]
env-llmeval/lib/python3.10/site-packages/pandas/api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (377 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/api/extensions/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public API for extending pandas objects.
3
+ """
4
+
5
+ from pandas._libs.lib import no_default
6
+
7
+ from pandas.core.dtypes.base import (
8
+ ExtensionDtype,
9
+ register_extension_dtype,
10
+ )
11
+
12
+ from pandas.core.accessor import (
13
+ register_dataframe_accessor,
14
+ register_index_accessor,
15
+ register_series_accessor,
16
+ )
17
+ from pandas.core.algorithms import take
18
+ from pandas.core.arrays import (
19
+ ExtensionArray,
20
+ ExtensionScalarOpsMixin,
21
+ )
22
+
23
+ __all__ = [
24
+ "no_default",
25
+ "ExtensionDtype",
26
+ "register_extension_dtype",
27
+ "register_dataframe_accessor",
28
+ "register_index_accessor",
29
+ "register_series_accessor",
30
+ "take",
31
+ "ExtensionArray",
32
+ "ExtensionScalarOpsMixin",
33
+ ]
env-llmeval/lib/python3.10/site-packages/pandas/api/extensions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (742 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/api/indexers/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public API for Rolling Window Indexers.
3
+ """
4
+
5
+ from pandas.core.indexers import check_array_indexer
6
+ from pandas.core.indexers.objects import (
7
+ BaseIndexer,
8
+ FixedForwardWindowIndexer,
9
+ VariableOffsetWindowIndexer,
10
+ )
11
+
12
+ __all__ = [
13
+ "check_array_indexer",
14
+ "BaseIndexer",
15
+ "FixedForwardWindowIndexer",
16
+ "VariableOffsetWindowIndexer",
17
+ ]
env-llmeval/lib/python3.10/site-packages/pandas/api/indexers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (485 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/api/interchange/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public API for DataFrame interchange protocol.
3
+ """
4
+
5
+ from pandas.core.interchange.dataframe_protocol import DataFrame
6
+ from pandas.core.interchange.from_dataframe import from_dataframe
7
+
8
+ __all__ = ["from_dataframe", "DataFrame"]
env-llmeval/lib/python3.10/site-packages/pandas/api/interchange/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (434 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/api/types/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public toolkit API.
3
+ """
4
+
5
+ from pandas._libs.lib import infer_dtype
6
+
7
+ from pandas.core.dtypes.api import * # noqa: F403
8
+ from pandas.core.dtypes.concat import union_categoricals
9
+ from pandas.core.dtypes.dtypes import (
10
+ CategoricalDtype,
11
+ DatetimeTZDtype,
12
+ IntervalDtype,
13
+ PeriodDtype,
14
+ )
15
+
16
+ __all__ = [
17
+ "infer_dtype",
18
+ "union_categoricals",
19
+ "CategoricalDtype",
20
+ "DatetimeTZDtype",
21
+ "IntervalDtype",
22
+ "PeriodDtype",
23
+ ]
env-llmeval/lib/python3.10/site-packages/pandas/api/types/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (567 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/api/typing/__init__.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public API classes that store intermediate results useful for type-hinting.
3
+ """
4
+
5
+ from pandas._libs import NaTType
6
+ from pandas._libs.missing import NAType
7
+
8
+ from pandas.core.groupby import (
9
+ DataFrameGroupBy,
10
+ SeriesGroupBy,
11
+ )
12
+ from pandas.core.resample import (
13
+ DatetimeIndexResamplerGroupby,
14
+ PeriodIndexResamplerGroupby,
15
+ Resampler,
16
+ TimedeltaIndexResamplerGroupby,
17
+ TimeGrouper,
18
+ )
19
+ from pandas.core.window import (
20
+ Expanding,
21
+ ExpandingGroupby,
22
+ ExponentialMovingWindow,
23
+ ExponentialMovingWindowGroupby,
24
+ Rolling,
25
+ RollingGroupby,
26
+ Window,
27
+ )
28
+
29
+ # TODO: Can't import Styler without importing jinja2
30
+ # from pandas.io.formats.style import Styler
31
+ from pandas.io.json._json import JsonReader
32
+ from pandas.io.stata import StataReader
33
+
34
+ __all__ = [
35
+ "DataFrameGroupBy",
36
+ "DatetimeIndexResamplerGroupby",
37
+ "Expanding",
38
+ "ExpandingGroupby",
39
+ "ExponentialMovingWindow",
40
+ "ExponentialMovingWindowGroupby",
41
+ "JsonReader",
42
+ "NaTType",
43
+ "NAType",
44
+ "PeriodIndexResamplerGroupby",
45
+ "Resampler",
46
+ "Rolling",
47
+ "RollingGroupby",
48
+ "SeriesGroupBy",
49
+ "StataReader",
50
+ # See TODO above
51
+ # "Styler",
52
+ "TimedeltaIndexResamplerGroupby",
53
+ "TimeGrouper",
54
+ "Window",
55
+ ]
env-llmeval/lib/python3.10/site-packages/pandas/api/typing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (633 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_calamine.cpython-310.pyc ADDED
Binary file (4.35 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_util.cpython-310.pyc ADDED
Binary file (8.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_xlrd.cpython-310.pyc ADDED
Binary file (4.23 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/io/excel/__pycache__/_xlsxwriter.cpython-310.pyc ADDED
Binary file (6.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (5.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (2.03 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_contains.cpython-310.pyc ADDED
Binary file (2.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_formats.cpython-310.pyc ADDED
Binary file (587 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_interval.cpython-310.pyc ADDED
Binary file (2.48 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/interval/__pycache__/test_overlaps.cpython-310.pyc ADDED
Binary file (2.63 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/period/__init__.py ADDED
File without changes
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/period/test_period.py ADDED
@@ -0,0 +1,1154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ date,
3
+ datetime,
4
+ timedelta,
5
+ )
6
+ import re
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas._libs.tslibs import iNaT
12
+ from pandas._libs.tslibs.ccalendar import (
13
+ DAYS,
14
+ MONTHS,
15
+ )
16
+ from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
17
+ from pandas._libs.tslibs.parsing import DateParseError
18
+ from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
19
+
20
+ from pandas import (
21
+ NaT,
22
+ Period,
23
+ Timedelta,
24
+ Timestamp,
25
+ offsets,
26
+ )
27
+ import pandas._testing as tm
28
+
29
+ bday_msg = "Period with BDay freq is deprecated"
30
+
31
+
32
+ class TestPeriodDisallowedFreqs:
33
+ @pytest.mark.parametrize(
34
+ "freq, freq_msg",
35
+ [
36
+ (offsets.BYearBegin(), "BYearBegin"),
37
+ (offsets.YearBegin(2), "YearBegin"),
38
+ (offsets.QuarterBegin(startingMonth=12), "QuarterBegin"),
39
+ (offsets.BusinessMonthEnd(2), "BusinessMonthEnd"),
40
+ ],
41
+ )
42
+ def test_offsets_not_supported(self, freq, freq_msg):
43
+ # GH#55785
44
+ msg = re.escape(f"{freq} is not supported as period frequency")
45
+ with pytest.raises(ValueError, match=msg):
46
+ Period(year=2014, freq=freq)
47
+
48
+ def test_custom_business_day_freq_raises(self):
49
+ # GH#52534
50
+ msg = "C is not supported as period frequency"
51
+ with pytest.raises(ValueError, match=msg):
52
+ Period("2023-04-10", freq="C")
53
+ msg = f"{offsets.CustomBusinessDay().base} is not supported as period frequency"
54
+ with pytest.raises(ValueError, match=msg):
55
+ Period("2023-04-10", freq=offsets.CustomBusinessDay())
56
+
57
+ def test_invalid_frequency_error_message(self):
58
+ msg = "WOM-1MON is not supported as period frequency"
59
+ with pytest.raises(ValueError, match=msg):
60
+ Period("2012-01-02", freq="WOM-1MON")
61
+
62
+ def test_invalid_frequency_period_error_message(self):
63
+ msg = "for Period, please use 'M' instead of 'ME'"
64
+ with pytest.raises(ValueError, match=msg):
65
+ Period("2012-01-02", freq="ME")
66
+
67
+
68
+ class TestPeriodConstruction:
69
+ def test_from_td64nat_raises(self):
70
+ # GH#44507
71
+ td = NaT.to_numpy("m8[ns]")
72
+
73
+ msg = "Value must be Period, string, integer, or datetime"
74
+ with pytest.raises(ValueError, match=msg):
75
+ Period(td)
76
+
77
+ with pytest.raises(ValueError, match=msg):
78
+ Period(td, freq="D")
79
+
80
+ def test_construction(self):
81
+ i1 = Period("1/1/2005", freq="M")
82
+ i2 = Period("Jan 2005")
83
+
84
+ assert i1 == i2
85
+
86
+ # GH#54105 - Period can be confusingly instantiated with lowercase freq
87
+ # TODO: raise in the future an error when passing lowercase freq
88
+ i1 = Period("2005", freq="Y")
89
+ i2 = Period("2005")
90
+
91
+ assert i1 == i2
92
+
93
+ i4 = Period("2005", freq="M")
94
+ assert i1 != i4
95
+
96
+ i1 = Period.now(freq="Q")
97
+ i2 = Period(datetime.now(), freq="Q")
98
+
99
+ assert i1 == i2
100
+
101
+ # Pass in freq as a keyword argument sometimes as a test for
102
+ # https://github.com/pandas-dev/pandas/issues/53369
103
+ i1 = Period.now(freq="D")
104
+ i2 = Period(datetime.now(), freq="D")
105
+ i3 = Period.now(offsets.Day())
106
+
107
+ assert i1 == i2
108
+ assert i1 == i3
109
+
110
+ i1 = Period("1982", freq="min")
111
+ msg = "'MIN' is deprecated and will be removed in a future version."
112
+ with tm.assert_produces_warning(FutureWarning, match=msg):
113
+ i2 = Period("1982", freq="MIN")
114
+ assert i1 == i2
115
+
116
+ i1 = Period(year=2005, month=3, day=1, freq="D")
117
+ i2 = Period("3/1/2005", freq="D")
118
+ assert i1 == i2
119
+
120
+ i3 = Period(year=2005, month=3, day=1, freq="d")
121
+ assert i1 == i3
122
+
123
+ i1 = Period("2007-01-01 09:00:00.001")
124
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")
125
+ assert i1 == expected
126
+
127
+ expected = Period("2007-01-01 09:00:00.001", freq="ms")
128
+ assert i1 == expected
129
+
130
+ i1 = Period("2007-01-01 09:00:00.00101")
131
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")
132
+ assert i1 == expected
133
+
134
+ expected = Period("2007-01-01 09:00:00.00101", freq="us")
135
+ assert i1 == expected
136
+
137
+ msg = "Must supply freq for ordinal value"
138
+ with pytest.raises(ValueError, match=msg):
139
+ Period(ordinal=200701)
140
+
141
+ msg = "Invalid frequency: X"
142
+ with pytest.raises(ValueError, match=msg):
143
+ Period("2007-1-1", freq="X")
144
+
145
+ def test_tuple_freq_disallowed(self):
146
+ # GH#34703 tuple freq disallowed
147
+ with pytest.raises(TypeError, match="pass as a string instead"):
148
+ Period("1982", freq=("Min", 1))
149
+
150
+ with pytest.raises(TypeError, match="pass as a string instead"):
151
+ Period("2006-12-31", ("w", 1))
152
+
153
+ def test_construction_from_timestamp_nanos(self):
154
+ # GH#46811 don't drop nanos from Timestamp
155
+ ts = Timestamp("2022-04-20 09:23:24.123456789")
156
+ per = Period(ts, freq="ns")
157
+
158
+ # should losslessly round-trip, not lose the 789
159
+ rt = per.to_timestamp()
160
+ assert rt == ts
161
+
162
+ # same thing but from a datetime64 object
163
+ dt64 = ts.asm8
164
+ per2 = Period(dt64, freq="ns")
165
+ rt2 = per2.to_timestamp()
166
+ assert rt2.asm8 == dt64
167
+
168
+ def test_construction_bday(self):
169
+ # Biz day construction, roll forward if non-weekday
170
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
171
+ i1 = Period("3/10/12", freq="B")
172
+ i2 = Period("3/10/12", freq="D")
173
+ assert i1 == i2.asfreq("B")
174
+ i2 = Period("3/11/12", freq="D")
175
+ assert i1 == i2.asfreq("B")
176
+ i2 = Period("3/12/12", freq="D")
177
+ assert i1 == i2.asfreq("B")
178
+
179
+ i3 = Period("3/10/12", freq="b")
180
+ assert i1 == i3
181
+
182
+ i1 = Period(year=2012, month=3, day=10, freq="B")
183
+ i2 = Period("3/12/12", freq="B")
184
+ assert i1 == i2
185
+
186
+ def test_construction_quarter(self):
187
+ i1 = Period(year=2005, quarter=1, freq="Q")
188
+ i2 = Period("1/1/2005", freq="Q")
189
+ assert i1 == i2
190
+
191
+ i1 = Period(year=2005, quarter=3, freq="Q")
192
+ i2 = Period("9/1/2005", freq="Q")
193
+ assert i1 == i2
194
+
195
+ i1 = Period("2005Q1")
196
+ i2 = Period(year=2005, quarter=1, freq="Q")
197
+ i3 = Period("2005q1")
198
+ assert i1 == i2
199
+ assert i1 == i3
200
+
201
+ i1 = Period("05Q1")
202
+ assert i1 == i2
203
+ lower = Period("05q1")
204
+ assert i1 == lower
205
+
206
+ i1 = Period("1Q2005")
207
+ assert i1 == i2
208
+ lower = Period("1q2005")
209
+ assert i1 == lower
210
+
211
+ i1 = Period("1Q05")
212
+ assert i1 == i2
213
+ lower = Period("1q05")
214
+ assert i1 == lower
215
+
216
+ i1 = Period("4Q1984")
217
+ assert i1.year == 1984
218
+ lower = Period("4q1984")
219
+ assert i1 == lower
220
+
221
+ def test_construction_month(self):
222
+ expected = Period("2007-01", freq="M")
223
+ i1 = Period("200701", freq="M")
224
+ assert i1 == expected
225
+
226
+ i1 = Period("200701", freq="M")
227
+ assert i1 == expected
228
+
229
+ i1 = Period(200701, freq="M")
230
+ assert i1 == expected
231
+
232
+ i1 = Period(ordinal=200701, freq="M")
233
+ assert i1.year == 18695
234
+
235
+ i1 = Period(datetime(2007, 1, 1), freq="M")
236
+ i2 = Period("200701", freq="M")
237
+ assert i1 == i2
238
+
239
+ i1 = Period(date(2007, 1, 1), freq="M")
240
+ i2 = Period(datetime(2007, 1, 1), freq="M")
241
+ i3 = Period(np.datetime64("2007-01-01"), freq="M")
242
+ i4 = Period("2007-01-01 00:00:00", freq="M")
243
+ i5 = Period("2007-01-01 00:00:00.000", freq="M")
244
+ assert i1 == i2
245
+ assert i1 == i3
246
+ assert i1 == i4
247
+ assert i1 == i5
248
+
249
+ def test_period_constructor_offsets(self):
250
+ assert Period("1/1/2005", freq=offsets.MonthEnd()) == Period(
251
+ "1/1/2005", freq="M"
252
+ )
253
+ assert Period("2005", freq=offsets.YearEnd()) == Period("2005", freq="Y")
254
+ assert Period("2005", freq=offsets.MonthEnd()) == Period("2005", freq="M")
255
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
256
+ assert Period("3/10/12", freq=offsets.BusinessDay()) == Period(
257
+ "3/10/12", freq="B"
258
+ )
259
+ assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D")
260
+
261
+ assert Period(
262
+ year=2005, quarter=1, freq=offsets.QuarterEnd(startingMonth=12)
263
+ ) == Period(year=2005, quarter=1, freq="Q")
264
+ assert Period(
265
+ year=2005, quarter=2, freq=offsets.QuarterEnd(startingMonth=12)
266
+ ) == Period(year=2005, quarter=2, freq="Q")
267
+
268
+ assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period(
269
+ year=2005, month=3, day=1, freq="D"
270
+ )
271
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
272
+ assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period(
273
+ year=2012, month=3, day=10, freq="B"
274
+ )
275
+
276
+ expected = Period("2005-03-01", freq="3D")
277
+ assert Period(year=2005, month=3, day=1, freq=offsets.Day(3)) == expected
278
+ assert Period(year=2005, month=3, day=1, freq="3D") == expected
279
+
280
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
281
+ assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period(
282
+ year=2012, month=3, day=10, freq="3B"
283
+ )
284
+
285
+ assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M")
286
+
287
+ i1 = Period(ordinal=200701, freq=offsets.MonthEnd())
288
+ i2 = Period(ordinal=200701, freq="M")
289
+ assert i1 == i2
290
+ assert i1.year == 18695
291
+ assert i2.year == 18695
292
+
293
+ i1 = Period(datetime(2007, 1, 1), freq="M")
294
+ i2 = Period("200701", freq="M")
295
+ assert i1 == i2
296
+
297
+ i1 = Period(date(2007, 1, 1), freq="M")
298
+ i2 = Period(datetime(2007, 1, 1), freq="M")
299
+ i3 = Period(np.datetime64("2007-01-01"), freq="M")
300
+ i4 = Period("2007-01-01 00:00:00", freq="M")
301
+ i5 = Period("2007-01-01 00:00:00.000", freq="M")
302
+ assert i1 == i2
303
+ assert i1 == i3
304
+ assert i1 == i4
305
+ assert i1 == i5
306
+
307
+ i1 = Period("2007-01-01 09:00:00.001")
308
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")
309
+ assert i1 == expected
310
+
311
+ expected = Period("2007-01-01 09:00:00.001", freq="ms")
312
+ assert i1 == expected
313
+
314
+ i1 = Period("2007-01-01 09:00:00.00101")
315
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")
316
+ assert i1 == expected
317
+
318
+ expected = Period("2007-01-01 09:00:00.00101", freq="us")
319
+ assert i1 == expected
320
+
321
+ def test_invalid_arguments(self):
322
+ msg = "Must supply freq for datetime value"
323
+ with pytest.raises(ValueError, match=msg):
324
+ Period(datetime.now())
325
+ with pytest.raises(ValueError, match=msg):
326
+ Period(datetime.now().date())
327
+
328
+ msg = "Value must be Period, string, integer, or datetime"
329
+ with pytest.raises(ValueError, match=msg):
330
+ Period(1.6, freq="D")
331
+ msg = "Ordinal must be an integer"
332
+ with pytest.raises(ValueError, match=msg):
333
+ Period(ordinal=1.6, freq="D")
334
+ msg = "Only value or ordinal but not both should be given but not both"
335
+ with pytest.raises(ValueError, match=msg):
336
+ Period(ordinal=2, value=1, freq="D")
337
+
338
+ msg = "If value is None, freq cannot be None"
339
+ with pytest.raises(ValueError, match=msg):
340
+ Period(month=1)
341
+
342
+ msg = '^Given date string "-2000" not likely a datetime$'
343
+ with pytest.raises(ValueError, match=msg):
344
+ Period("-2000", "Y")
345
+ msg = "day is out of range for month"
346
+ with pytest.raises(DateParseError, match=msg):
347
+ Period("0", "Y")
348
+ msg = "Unknown datetime string format, unable to parse"
349
+ with pytest.raises(DateParseError, match=msg):
350
+ Period("1/1/-2000", "Y")
351
+
352
+ def test_constructor_corner(self):
353
+ expected = Period("2007-01", freq="2M")
354
+ assert Period(year=2007, month=1, freq="2M") == expected
355
+
356
+ assert Period(None) is NaT
357
+
358
+ p = Period("2007-01-01", freq="D")
359
+
360
+ result = Period(p, freq="Y")
361
+ exp = Period("2007", freq="Y")
362
+ assert result == exp
363
+
364
+ def test_constructor_infer_freq(self):
365
+ p = Period("2007-01-01")
366
+ assert p.freq == "D"
367
+
368
+ p = Period("2007-01-01 07")
369
+ assert p.freq == "h"
370
+
371
+ p = Period("2007-01-01 07:10")
372
+ assert p.freq == "min"
373
+
374
+ p = Period("2007-01-01 07:10:15")
375
+ assert p.freq == "s"
376
+
377
+ p = Period("2007-01-01 07:10:15.123")
378
+ assert p.freq == "ms"
379
+
380
+ # We see that there are 6 digits after the decimal, so get microsecond
381
+ # even though they are all zeros.
382
+ p = Period("2007-01-01 07:10:15.123000")
383
+ assert p.freq == "us"
384
+
385
+ p = Period("2007-01-01 07:10:15.123400")
386
+ assert p.freq == "us"
387
+
388
+ def test_multiples(self):
389
+ result1 = Period("1989", freq="2Y")
390
+ result2 = Period("1989", freq="Y")
391
+ assert result1.ordinal == result2.ordinal
392
+ assert result1.freqstr == "2Y-DEC"
393
+ assert result2.freqstr == "Y-DEC"
394
+ assert result1.freq == offsets.YearEnd(2)
395
+ assert result2.freq == offsets.YearEnd()
396
+
397
+ assert (result1 + 1).ordinal == result1.ordinal + 2
398
+ assert (1 + result1).ordinal == result1.ordinal + 2
399
+ assert (result1 - 1).ordinal == result2.ordinal - 2
400
+ assert (-1 + result1).ordinal == result2.ordinal - 2
401
+
402
+ @pytest.mark.parametrize("month", MONTHS)
403
+ def test_period_cons_quarterly(self, month):
404
+ # bugs in scikits.timeseries
405
+ freq = f"Q-{month}"
406
+ exp = Period("1989Q3", freq=freq)
407
+ assert "1989Q3" in str(exp)
408
+ stamp = exp.to_timestamp("D", how="end")
409
+ p = Period(stamp, freq=freq)
410
+ assert p == exp
411
+
412
+ stamp = exp.to_timestamp("3D", how="end")
413
+ p = Period(stamp, freq=freq)
414
+ assert p == exp
415
+
416
+ @pytest.mark.parametrize("month", MONTHS)
417
+ def test_period_cons_annual(self, month):
418
+ # bugs in scikits.timeseries
419
+ freq = f"Y-{month}"
420
+ exp = Period("1989", freq=freq)
421
+ stamp = exp.to_timestamp("D", how="end") + timedelta(days=30)
422
+ p = Period(stamp, freq=freq)
423
+
424
+ assert p == exp + 1
425
+ assert isinstance(p, Period)
426
+
427
+ @pytest.mark.parametrize("day", DAYS)
428
+ @pytest.mark.parametrize("num", range(10, 17))
429
+ def test_period_cons_weekly(self, num, day):
430
+ daystr = f"2011-02-{num}"
431
+ freq = f"W-{day}"
432
+
433
+ result = Period(daystr, freq=freq)
434
+ expected = Period(daystr, freq="D").asfreq(freq)
435
+ assert result == expected
436
+ assert isinstance(result, Period)
437
+
438
+ def test_parse_week_str_roundstrip(self):
439
+ # GH#50803
440
+ per = Period("2017-01-23/2017-01-29")
441
+ assert per.freq.freqstr == "W-SUN"
442
+
443
+ per = Period("2017-01-24/2017-01-30")
444
+ assert per.freq.freqstr == "W-MON"
445
+
446
+ msg = "Could not parse as weekly-freq Period"
447
+ with pytest.raises(ValueError, match=msg):
448
+ # not 6 days apart
449
+ Period("2016-01-23/2017-01-29")
450
+
451
+ def test_period_from_ordinal(self):
452
+ p = Period("2011-01", freq="M")
453
+ res = Period._from_ordinal(p.ordinal, freq=p.freq)
454
+ assert p == res
455
+ assert isinstance(res, Period)
456
+
457
+ @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])
458
+ def test_construct_from_nat_string_and_freq(self, freq):
459
+ per = Period("NaT", freq=freq)
460
+ assert per is NaT
461
+
462
+ per = Period("NaT", freq="2" + freq)
463
+ assert per is NaT
464
+
465
+ per = Period("NaT", freq="3" + freq)
466
+ assert per is NaT
467
+
468
+ def test_period_cons_nat(self):
469
+ p = Period("nat", freq="W-SUN")
470
+ assert p is NaT
471
+
472
+ p = Period(iNaT, freq="D")
473
+ assert p is NaT
474
+
475
+ p = Period(iNaT, freq="3D")
476
+ assert p is NaT
477
+
478
+ p = Period(iNaT, freq="1D1h")
479
+ assert p is NaT
480
+
481
+ p = Period("NaT")
482
+ assert p is NaT
483
+
484
+ p = Period(iNaT)
485
+ assert p is NaT
486
+
487
+ def test_period_cons_mult(self):
488
+ p1 = Period("2011-01", freq="3M")
489
+ p2 = Period("2011-01", freq="M")
490
+ assert p1.ordinal == p2.ordinal
491
+
492
+ assert p1.freq == offsets.MonthEnd(3)
493
+ assert p1.freqstr == "3M"
494
+
495
+ assert p2.freq == offsets.MonthEnd()
496
+ assert p2.freqstr == "M"
497
+
498
+ result = p1 + 1
499
+ assert result.ordinal == (p2 + 3).ordinal
500
+
501
+ assert result.freq == p1.freq
502
+ assert result.freqstr == "3M"
503
+
504
+ result = p1 - 1
505
+ assert result.ordinal == (p2 - 3).ordinal
506
+ assert result.freq == p1.freq
507
+ assert result.freqstr == "3M"
508
+
509
+ msg = "Frequency must be positive, because it represents span: -3M"
510
+ with pytest.raises(ValueError, match=msg):
511
+ Period("2011-01", freq="-3M")
512
+
513
+ msg = "Frequency must be positive, because it represents span: 0M"
514
+ with pytest.raises(ValueError, match=msg):
515
+ Period("2011-01", freq="0M")
516
+
517
+ def test_period_cons_combined(self):
518
+ p = [
519
+ (
520
+ Period("2011-01", freq="1D1h"),
521
+ Period("2011-01", freq="1h1D"),
522
+ Period("2011-01", freq="h"),
523
+ ),
524
+ (
525
+ Period(ordinal=1, freq="1D1h"),
526
+ Period(ordinal=1, freq="1h1D"),
527
+ Period(ordinal=1, freq="h"),
528
+ ),
529
+ ]
530
+
531
+ for p1, p2, p3 in p:
532
+ assert p1.ordinal == p3.ordinal
533
+ assert p2.ordinal == p3.ordinal
534
+
535
+ assert p1.freq == offsets.Hour(25)
536
+ assert p1.freqstr == "25h"
537
+
538
+ assert p2.freq == offsets.Hour(25)
539
+ assert p2.freqstr == "25h"
540
+
541
+ assert p3.freq == offsets.Hour()
542
+ assert p3.freqstr == "h"
543
+
544
+ result = p1 + 1
545
+ assert result.ordinal == (p3 + 25).ordinal
546
+ assert result.freq == p1.freq
547
+ assert result.freqstr == "25h"
548
+
549
+ result = p2 + 1
550
+ assert result.ordinal == (p3 + 25).ordinal
551
+ assert result.freq == p2.freq
552
+ assert result.freqstr == "25h"
553
+
554
+ result = p1 - 1
555
+ assert result.ordinal == (p3 - 25).ordinal
556
+ assert result.freq == p1.freq
557
+ assert result.freqstr == "25h"
558
+
559
+ result = p2 - 1
560
+ assert result.ordinal == (p3 - 25).ordinal
561
+ assert result.freq == p2.freq
562
+ assert result.freqstr == "25h"
563
+
564
+ msg = "Frequency must be positive, because it represents span: -25h"
565
+ with pytest.raises(ValueError, match=msg):
566
+ Period("2011-01", freq="-1D1h")
567
+ with pytest.raises(ValueError, match=msg):
568
+ Period("2011-01", freq="-1h1D")
569
+ with pytest.raises(ValueError, match=msg):
570
+ Period(ordinal=1, freq="-1D1h")
571
+ with pytest.raises(ValueError, match=msg):
572
+ Period(ordinal=1, freq="-1h1D")
573
+
574
+ msg = "Frequency must be positive, because it represents span: 0D"
575
+ with pytest.raises(ValueError, match=msg):
576
+ Period("2011-01", freq="0D0h")
577
+ with pytest.raises(ValueError, match=msg):
578
+ Period(ordinal=1, freq="0D0h")
579
+
580
+ # You can only combine together day and intraday offsets
581
+ msg = "Invalid frequency: 1W1D"
582
+ with pytest.raises(ValueError, match=msg):
583
+ Period("2011-01", freq="1W1D")
584
+ msg = "Invalid frequency: 1D1W"
585
+ with pytest.raises(ValueError, match=msg):
586
+ Period("2011-01", freq="1D1W")
587
+
588
+ @pytest.mark.parametrize("day", ["1970/01/01 ", "2020-12-31 ", "1981/09/13 "])
589
+ @pytest.mark.parametrize("hour", ["00:00:00", "00:00:01", "23:59:59", "12:00:59"])
590
+ @pytest.mark.parametrize(
591
+ "sec_float, expected",
592
+ [
593
+ (".000000001", 1),
594
+ (".000000999", 999),
595
+ (".123456789", 789),
596
+ (".999999999", 999),
597
+ (".999999000", 0),
598
+ # Test femtoseconds, attoseconds, picoseconds are dropped like Timestamp
599
+ (".999999001123", 1),
600
+ (".999999001123456", 1),
601
+ (".999999001123456789", 1),
602
+ ],
603
+ )
604
+ def test_period_constructor_nanosecond(self, day, hour, sec_float, expected):
605
+ # GH 34621
606
+
607
+ assert Period(day + hour + sec_float).start_time.nanosecond == expected
608
+
609
+ @pytest.mark.parametrize("hour", range(24))
610
+ def test_period_large_ordinal(self, hour):
611
+ # Issue #36430
612
+ # Integer overflow for Period over the maximum timestamp
613
+ p = Period(ordinal=2562048 + hour, freq="1h")
614
+ assert p.hour == hour
615
+
616
+
617
+ class TestPeriodMethods:
618
+ def test_round_trip(self):
619
+ p = Period("2000Q1")
620
+ new_p = tm.round_trip_pickle(p)
621
+ assert new_p == p
622
+
623
+ def test_hash(self):
624
+ assert hash(Period("2011-01", freq="M")) == hash(Period("2011-01", freq="M"))
625
+
626
+ assert hash(Period("2011-01-01", freq="D")) != hash(Period("2011-01", freq="M"))
627
+
628
+ assert hash(Period("2011-01", freq="3M")) != hash(Period("2011-01", freq="2M"))
629
+
630
+ assert hash(Period("2011-01", freq="M")) != hash(Period("2011-02", freq="M"))
631
+
632
+ # --------------------------------------------------------------
633
+ # to_timestamp
634
+
635
+ def test_to_timestamp_mult(self):
636
+ p = Period("2011-01", freq="M")
637
+ assert p.to_timestamp(how="S") == Timestamp("2011-01-01")
638
+ expected = Timestamp("2011-02-01") - Timedelta(1, "ns")
639
+ assert p.to_timestamp(how="E") == expected
640
+
641
+ p = Period("2011-01", freq="3M")
642
+ assert p.to_timestamp(how="S") == Timestamp("2011-01-01")
643
+ expected = Timestamp("2011-04-01") - Timedelta(1, "ns")
644
+ assert p.to_timestamp(how="E") == expected
645
+
646
+ @pytest.mark.filterwarnings(
647
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
648
+ )
649
+ def test_to_timestamp(self):
650
+ p = Period("1982", freq="Y")
651
+ start_ts = p.to_timestamp(how="S")
652
+ aliases = ["s", "StarT", "BEGIn"]
653
+ for a in aliases:
654
+ assert start_ts == p.to_timestamp("D", how=a)
655
+ # freq with mult should not affect to the result
656
+ assert start_ts == p.to_timestamp("3D", how=a)
657
+
658
+ end_ts = p.to_timestamp(how="E")
659
+ aliases = ["e", "end", "FINIsH"]
660
+ for a in aliases:
661
+ assert end_ts == p.to_timestamp("D", how=a)
662
+ assert end_ts == p.to_timestamp("3D", how=a)
663
+
664
+ from_lst = ["Y", "Q", "M", "W", "B", "D", "h", "Min", "s"]
665
+
666
+ def _ex(p):
667
+ if p.freq == "B":
668
+ return p.start_time + Timedelta(days=1, nanoseconds=-1)
669
+ return Timestamp((p + p.freq).start_time._value - 1)
670
+
671
+ for fcode in from_lst:
672
+ p = Period("1982", freq=fcode)
673
+ result = p.to_timestamp().to_period(fcode)
674
+ assert result == p
675
+
676
+ assert p.start_time == p.to_timestamp(how="S")
677
+
678
+ assert p.end_time == _ex(p)
679
+
680
+ # Frequency other than daily
681
+
682
+ p = Period("1985", freq="Y")
683
+
684
+ result = p.to_timestamp("h", how="end")
685
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
686
+ assert result == expected
687
+ result = p.to_timestamp("3h", how="end")
688
+ assert result == expected
689
+
690
+ result = p.to_timestamp("min", how="end")
691
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
692
+ assert result == expected
693
+ result = p.to_timestamp("2min", how="end")
694
+ assert result == expected
695
+
696
+ result = p.to_timestamp(how="end")
697
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
698
+ assert result == expected
699
+
700
+ expected = datetime(1985, 1, 1)
701
+ result = p.to_timestamp("h", how="start")
702
+ assert result == expected
703
+ result = p.to_timestamp("min", how="start")
704
+ assert result == expected
705
+ result = p.to_timestamp("s", how="start")
706
+ assert result == expected
707
+ result = p.to_timestamp("3h", how="start")
708
+ assert result == expected
709
+ result = p.to_timestamp("5s", how="start")
710
+ assert result == expected
711
+
712
+ def test_to_timestamp_business_end(self):
713
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
714
+ per = Period("1990-01-05", "B") # Friday
715
+ result = per.to_timestamp("B", how="E")
716
+
717
+ expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)
718
+ assert result == expected
719
+
720
+ @pytest.mark.parametrize(
721
+ "ts, expected",
722
+ [
723
+ ("1970-01-01 00:00:00", 0),
724
+ ("1970-01-01 00:00:00.000001", 1),
725
+ ("1970-01-01 00:00:00.00001", 10),
726
+ ("1970-01-01 00:00:00.499", 499000),
727
+ ("1999-12-31 23:59:59.999", 999000),
728
+ ("1999-12-31 23:59:59.999999", 999999),
729
+ ("2050-12-31 23:59:59.5", 500000),
730
+ ("2050-12-31 23:59:59.500001", 500001),
731
+ ("2050-12-31 23:59:59.123456", 123456),
732
+ ],
733
+ )
734
+ @pytest.mark.parametrize("freq", [None, "us", "ns"])
735
+ def test_to_timestamp_microsecond(self, ts, expected, freq):
736
+ # GH 24444
737
+ result = Period(ts).to_timestamp(freq=freq).microsecond
738
+ assert result == expected
739
+
740
+ # --------------------------------------------------------------
741
+ # Rendering: __repr__, strftime, etc
742
+
743
+ @pytest.mark.parametrize(
744
+ "str_ts,freq,str_res,str_freq",
745
+ (
746
+ ("Jan-2000", None, "2000-01", "M"),
747
+ ("2000-12-15", None, "2000-12-15", "D"),
748
+ (
749
+ "2000-12-15 13:45:26.123456789",
750
+ "ns",
751
+ "2000-12-15 13:45:26.123456789",
752
+ "ns",
753
+ ),
754
+ ("2000-12-15 13:45:26.123456789", "us", "2000-12-15 13:45:26.123456", "us"),
755
+ ("2000-12-15 13:45:26.123456", None, "2000-12-15 13:45:26.123456", "us"),
756
+ ("2000-12-15 13:45:26.123456789", "ms", "2000-12-15 13:45:26.123", "ms"),
757
+ ("2000-12-15 13:45:26.123", None, "2000-12-15 13:45:26.123", "ms"),
758
+ ("2000-12-15 13:45:26", "s", "2000-12-15 13:45:26", "s"),
759
+ ("2000-12-15 13:45:26", "min", "2000-12-15 13:45", "min"),
760
+ ("2000-12-15 13:45:26", "h", "2000-12-15 13:00", "h"),
761
+ ("2000-12-15", "Y", "2000", "Y-DEC"),
762
+ ("2000-12-15", "Q", "2000Q4", "Q-DEC"),
763
+ ("2000-12-15", "M", "2000-12", "M"),
764
+ ("2000-12-15", "W", "2000-12-11/2000-12-17", "W-SUN"),
765
+ ("2000-12-15", "D", "2000-12-15", "D"),
766
+ ("2000-12-15", "B", "2000-12-15", "B"),
767
+ ),
768
+ )
769
+ @pytest.mark.filterwarnings(
770
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
771
+ )
772
+ def test_repr(self, str_ts, freq, str_res, str_freq):
773
+ p = Period(str_ts, freq=freq)
774
+ assert str(p) == str_res
775
+ assert repr(p) == f"Period('{str_res}', '{str_freq}')"
776
+
777
+ def test_repr_nat(self):
778
+ p = Period("nat", freq="M")
779
+ assert repr(NaT) in repr(p)
780
+
781
+ def test_strftime(self):
782
+ # GH#3363
783
+ p = Period("2000-1-1 12:34:12", freq="s")
784
+ res = p.strftime("%Y-%m-%d %H:%M:%S")
785
+ assert res == "2000-01-01 12:34:12"
786
+ assert isinstance(res, str)
787
+
788
+
789
+ class TestPeriodProperties:
790
+ """Test properties such as year, month, weekday, etc...."""
791
+
792
+ @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])
793
+ def test_is_leap_year(self, freq):
794
+ # GH 13727
795
+ p = Period("2000-01-01 00:00:00", freq=freq)
796
+ assert p.is_leap_year
797
+ assert isinstance(p.is_leap_year, bool)
798
+
799
+ p = Period("1999-01-01 00:00:00", freq=freq)
800
+ assert not p.is_leap_year
801
+
802
+ p = Period("2004-01-01 00:00:00", freq=freq)
803
+ assert p.is_leap_year
804
+
805
+ p = Period("2100-01-01 00:00:00", freq=freq)
806
+ assert not p.is_leap_year
807
+
808
+ def test_quarterly_negative_ordinals(self):
809
+ p = Period(ordinal=-1, freq="Q-DEC")
810
+ assert p.year == 1969
811
+ assert p.quarter == 4
812
+ assert isinstance(p, Period)
813
+
814
+ p = Period(ordinal=-2, freq="Q-DEC")
815
+ assert p.year == 1969
816
+ assert p.quarter == 3
817
+ assert isinstance(p, Period)
818
+
819
+ p = Period(ordinal=-2, freq="M")
820
+ assert p.year == 1969
821
+ assert p.month == 11
822
+ assert isinstance(p, Period)
823
+
824
+ def test_freq_str(self):
825
+ i1 = Period("1982", freq="Min")
826
+ assert i1.freq == offsets.Minute()
827
+ assert i1.freqstr == "min"
828
+
829
+ @pytest.mark.filterwarnings(
830
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
831
+ )
832
+ def test_period_deprecated_freq(self):
833
+ cases = {
834
+ "M": ["MTH", "MONTH", "MONTHLY", "Mth", "month", "monthly"],
835
+ "B": ["BUS", "BUSINESS", "BUSINESSLY", "WEEKDAY", "bus"],
836
+ "D": ["DAY", "DLY", "DAILY", "Day", "Dly", "Daily"],
837
+ "h": ["HR", "HOUR", "HRLY", "HOURLY", "hr", "Hour", "HRly"],
838
+ "min": ["minute", "MINUTE", "MINUTELY", "minutely"],
839
+ "s": ["sec", "SEC", "SECOND", "SECONDLY", "second"],
840
+ "ms": ["MILLISECOND", "MILLISECONDLY", "millisecond"],
841
+ "us": ["MICROSECOND", "MICROSECONDLY", "microsecond"],
842
+ "ns": ["NANOSECOND", "NANOSECONDLY", "nanosecond"],
843
+ }
844
+
845
+ msg = INVALID_FREQ_ERR_MSG
846
+ for exp, freqs in cases.items():
847
+ for freq in freqs:
848
+ with pytest.raises(ValueError, match=msg):
849
+ Period("2016-03-01 09:00", freq=freq)
850
+ with pytest.raises(ValueError, match=msg):
851
+ Period(ordinal=1, freq=freq)
852
+
853
+ # check supported freq-aliases still works
854
+ p1 = Period("2016-03-01 09:00", freq=exp)
855
+ p2 = Period(ordinal=1, freq=exp)
856
+ assert isinstance(p1, Period)
857
+ assert isinstance(p2, Period)
858
+
859
+ @staticmethod
860
+ def _period_constructor(bound, offset):
861
+ return Period(
862
+ year=bound.year,
863
+ month=bound.month,
864
+ day=bound.day,
865
+ hour=bound.hour,
866
+ minute=bound.minute,
867
+ second=bound.second + offset,
868
+ freq="us",
869
+ )
870
+
871
+ @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])
872
+ @pytest.mark.parametrize("period_property", ["start_time", "end_time"])
873
+ def test_outer_bounds_start_and_end_time(self, bound, offset, period_property):
874
+ # GH #13346
875
+ period = TestPeriodProperties._period_constructor(bound, offset)
876
+ with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond"):
877
+ getattr(period, period_property)
878
+
879
+ @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])
880
+ @pytest.mark.parametrize("period_property", ["start_time", "end_time"])
881
+ def test_inner_bounds_start_and_end_time(self, bound, offset, period_property):
882
+ # GH #13346
883
+ period = TestPeriodProperties._period_constructor(bound, -offset)
884
+ expected = period.to_timestamp().round(freq="s")
885
+ assert getattr(period, period_property).round(freq="s") == expected
886
+ expected = (bound - offset * Timedelta(1, unit="s")).floor("s")
887
+ assert getattr(period, period_property).floor("s") == expected
888
+
889
+ def test_start_time(self):
890
+ freq_lst = ["Y", "Q", "M", "D", "h", "min", "s"]
891
+ xp = datetime(2012, 1, 1)
892
+ for f in freq_lst:
893
+ p = Period("2012", freq=f)
894
+ assert p.start_time == xp
895
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
896
+ assert Period("2012", freq="B").start_time == datetime(2012, 1, 2)
897
+ assert Period("2012", freq="W").start_time == datetime(2011, 12, 26)
898
+
899
+ def test_end_time(self):
900
+ p = Period("2012", freq="Y")
901
+
902
+ def _ex(*args):
903
+ return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)
904
+
905
+ xp = _ex(2013, 1, 1)
906
+ assert xp == p.end_time
907
+
908
+ p = Period("2012", freq="Q")
909
+ xp = _ex(2012, 4, 1)
910
+ assert xp == p.end_time
911
+
912
+ p = Period("2012", freq="M")
913
+ xp = _ex(2012, 2, 1)
914
+ assert xp == p.end_time
915
+
916
+ p = Period("2012", freq="D")
917
+ xp = _ex(2012, 1, 2)
918
+ assert xp == p.end_time
919
+
920
+ p = Period("2012", freq="h")
921
+ xp = _ex(2012, 1, 1, 1)
922
+ assert xp == p.end_time
923
+
924
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
925
+ p = Period("2012", freq="B")
926
+ xp = _ex(2012, 1, 3)
927
+ assert xp == p.end_time
928
+
929
+ p = Period("2012", freq="W")
930
+ xp = _ex(2012, 1, 2)
931
+ assert xp == p.end_time
932
+
933
+ # Test for GH 11738
934
+ p = Period("2012", freq="15D")
935
+ xp = _ex(2012, 1, 16)
936
+ assert xp == p.end_time
937
+
938
+ p = Period("2012", freq="1D1h")
939
+ xp = _ex(2012, 1, 2, 1)
940
+ assert xp == p.end_time
941
+
942
+ p = Period("2012", freq="1h1D")
943
+ xp = _ex(2012, 1, 2, 1)
944
+ assert xp == p.end_time
945
+
946
+ def test_end_time_business_friday(self):
947
+ # GH#34449
948
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
949
+ per = Period("1990-01-05", "B")
950
+ result = per.end_time
951
+
952
+ expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)
953
+ assert result == expected
954
+
955
+ def test_anchor_week_end_time(self):
956
+ def _ex(*args):
957
+ return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)
958
+
959
+ p = Period("2013-1-1", "W-SAT")
960
+ xp = _ex(2013, 1, 6)
961
+ assert p.end_time == xp
962
+
963
+ def test_properties_annually(self):
964
+ # Test properties on Periods with annually frequency.
965
+ a_date = Period(freq="Y", year=2007)
966
+ assert a_date.year == 2007
967
+
968
+ def test_properties_quarterly(self):
969
+ # Test properties on Periods with daily frequency.
970
+ qedec_date = Period(freq="Q-DEC", year=2007, quarter=1)
971
+ qejan_date = Period(freq="Q-JAN", year=2007, quarter=1)
972
+ qejun_date = Period(freq="Q-JUN", year=2007, quarter=1)
973
+ #
974
+ for x in range(3):
975
+ for qd in (qedec_date, qejan_date, qejun_date):
976
+ assert (qd + x).qyear == 2007
977
+ assert (qd + x).quarter == x + 1
978
+
979
+ def test_properties_monthly(self):
980
+ # Test properties on Periods with daily frequency.
981
+ m_date = Period(freq="M", year=2007, month=1)
982
+ for x in range(11):
983
+ m_ival_x = m_date + x
984
+ assert m_ival_x.year == 2007
985
+ if 1 <= x + 1 <= 3:
986
+ assert m_ival_x.quarter == 1
987
+ elif 4 <= x + 1 <= 6:
988
+ assert m_ival_x.quarter == 2
989
+ elif 7 <= x + 1 <= 9:
990
+ assert m_ival_x.quarter == 3
991
+ elif 10 <= x + 1 <= 12:
992
+ assert m_ival_x.quarter == 4
993
+ assert m_ival_x.month == x + 1
994
+
995
+ def test_properties_weekly(self):
996
+ # Test properties on Periods with daily frequency.
997
+ w_date = Period(freq="W", year=2007, month=1, day=7)
998
+ #
999
+ assert w_date.year == 2007
1000
+ assert w_date.quarter == 1
1001
+ assert w_date.month == 1
1002
+ assert w_date.week == 1
1003
+ assert (w_date - 1).week == 52
1004
+ assert w_date.days_in_month == 31
1005
+ assert Period(freq="W", year=2012, month=2, day=1).days_in_month == 29
1006
+
1007
+ def test_properties_weekly_legacy(self):
1008
+ # Test properties on Periods with daily frequency.
1009
+ w_date = Period(freq="W", year=2007, month=1, day=7)
1010
+ assert w_date.year == 2007
1011
+ assert w_date.quarter == 1
1012
+ assert w_date.month == 1
1013
+ assert w_date.week == 1
1014
+ assert (w_date - 1).week == 52
1015
+ assert w_date.days_in_month == 31
1016
+
1017
+ exp = Period(freq="W", year=2012, month=2, day=1)
1018
+ assert exp.days_in_month == 29
1019
+
1020
+ msg = INVALID_FREQ_ERR_MSG
1021
+ with pytest.raises(ValueError, match=msg):
1022
+ Period(freq="WK", year=2007, month=1, day=7)
1023
+
1024
+ def test_properties_daily(self):
1025
+ # Test properties on Periods with daily frequency.
1026
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1027
+ b_date = Period(freq="B", year=2007, month=1, day=1)
1028
+ #
1029
+ assert b_date.year == 2007
1030
+ assert b_date.quarter == 1
1031
+ assert b_date.month == 1
1032
+ assert b_date.day == 1
1033
+ assert b_date.weekday == 0
1034
+ assert b_date.dayofyear == 1
1035
+ assert b_date.days_in_month == 31
1036
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1037
+ assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29
1038
+
1039
+ d_date = Period(freq="D", year=2007, month=1, day=1)
1040
+
1041
+ assert d_date.year == 2007
1042
+ assert d_date.quarter == 1
1043
+ assert d_date.month == 1
1044
+ assert d_date.day == 1
1045
+ assert d_date.weekday == 0
1046
+ assert d_date.dayofyear == 1
1047
+ assert d_date.days_in_month == 31
1048
+ assert Period(freq="D", year=2012, month=2, day=1).days_in_month == 29
1049
+
1050
+ def test_properties_hourly(self):
1051
+ # Test properties on Periods with hourly frequency.
1052
+ h_date1 = Period(freq="h", year=2007, month=1, day=1, hour=0)
1053
+ h_date2 = Period(freq="2h", year=2007, month=1, day=1, hour=0)
1054
+
1055
+ for h_date in [h_date1, h_date2]:
1056
+ assert h_date.year == 2007
1057
+ assert h_date.quarter == 1
1058
+ assert h_date.month == 1
1059
+ assert h_date.day == 1
1060
+ assert h_date.weekday == 0
1061
+ assert h_date.dayofyear == 1
1062
+ assert h_date.hour == 0
1063
+ assert h_date.days_in_month == 31
1064
+ assert (
1065
+ Period(freq="h", year=2012, month=2, day=1, hour=0).days_in_month == 29
1066
+ )
1067
+
1068
+ def test_properties_minutely(self):
1069
+ # Test properties on Periods with minutely frequency.
1070
+ t_date = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0)
1071
+ #
1072
+ assert t_date.quarter == 1
1073
+ assert t_date.month == 1
1074
+ assert t_date.day == 1
1075
+ assert t_date.weekday == 0
1076
+ assert t_date.dayofyear == 1
1077
+ assert t_date.hour == 0
1078
+ assert t_date.minute == 0
1079
+ assert t_date.days_in_month == 31
1080
+ assert (
1081
+ Period(freq="D", year=2012, month=2, day=1, hour=0, minute=0).days_in_month
1082
+ == 29
1083
+ )
1084
+
1085
+ def test_properties_secondly(self):
1086
+ # Test properties on Periods with secondly frequency.
1087
+ s_date = Period(
1088
+ freq="Min", year=2007, month=1, day=1, hour=0, minute=0, second=0
1089
+ )
1090
+ #
1091
+ assert s_date.year == 2007
1092
+ assert s_date.quarter == 1
1093
+ assert s_date.month == 1
1094
+ assert s_date.day == 1
1095
+ assert s_date.weekday == 0
1096
+ assert s_date.dayofyear == 1
1097
+ assert s_date.hour == 0
1098
+ assert s_date.minute == 0
1099
+ assert s_date.second == 0
1100
+ assert s_date.days_in_month == 31
1101
+ assert (
1102
+ Period(
1103
+ freq="Min", year=2012, month=2, day=1, hour=0, minute=0, second=0
1104
+ ).days_in_month
1105
+ == 29
1106
+ )
1107
+
1108
+
1109
+ class TestPeriodComparisons:
1110
+ def test_sort_periods(self):
1111
+ jan = Period("2000-01", "M")
1112
+ feb = Period("2000-02", "M")
1113
+ mar = Period("2000-03", "M")
1114
+ periods = [mar, jan, feb]
1115
+ correctPeriods = [jan, feb, mar]
1116
+ assert sorted(periods) == correctPeriods
1117
+
1118
+
1119
+ def test_period_immutable():
1120
+ # see gh-17116
1121
+ msg = "not writable"
1122
+
1123
+ per = Period("2014Q1")
1124
+ with pytest.raises(AttributeError, match=msg):
1125
+ per.ordinal = 14
1126
+
1127
+ freq = per.freq
1128
+ with pytest.raises(AttributeError, match=msg):
1129
+ per.freq = 2 * freq
1130
+
1131
+
1132
+ def test_small_year_parsing():
1133
+ per1 = Period("0001-01-07", "D")
1134
+ assert per1.year == 1
1135
+ assert per1.day == 7
1136
+
1137
+
1138
+ def test_negone_ordinals():
1139
+ freqs = ["Y", "M", "Q", "D", "h", "min", "s"]
1140
+
1141
+ period = Period(ordinal=-1, freq="D")
1142
+ for freq in freqs:
1143
+ repr(period.asfreq(freq))
1144
+
1145
+ for freq in freqs:
1146
+ period = Period(ordinal=-1, freq=freq)
1147
+ repr(period)
1148
+ assert period.year == 1969
1149
+
1150
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1151
+ period = Period(ordinal=-1, freq="B")
1152
+ repr(period)
1153
+ period = Period(ordinal=-1, freq="W")
1154
+ repr(period)
env-llmeval/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)
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timedelta/__pycache__/test_arithmetic.cpython-310.pyc ADDED
Binary file (36.6 kB). View file
 
env-llmeval/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
env-llmeval/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
env-llmeval/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"
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_comparisons.cpython-310.pyc ADDED
Binary file (8.69 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (31.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_formats.cpython-310.pyc ADDED
Binary file (5.92 kB). View file
 
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/__pycache__/test_timezones.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
env-llmeval/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
+ )
env-llmeval/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
env-llmeval/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())
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_arithmetic.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ timezone,
5
+ )
6
+
7
+ from dateutil.tz import gettz
8
+ import numpy as np
9
+ import pytest
10
+ import pytz
11
+
12
+ from pandas._libs.tslibs import (
13
+ OutOfBoundsDatetime,
14
+ OutOfBoundsTimedelta,
15
+ Timedelta,
16
+ Timestamp,
17
+ offsets,
18
+ to_offset,
19
+ )
20
+
21
+ import pandas._testing as tm
22
+
23
+
24
+ class TestTimestampArithmetic:
25
+ def test_overflow_offset(self):
26
+ # no overflow expected
27
+
28
+ stamp = Timestamp("2000/1/1")
29
+ offset_no_overflow = to_offset("D") * 100
30
+
31
+ expected = Timestamp("2000/04/10")
32
+ assert stamp + offset_no_overflow == expected
33
+
34
+ assert offset_no_overflow + stamp == expected
35
+
36
+ expected = Timestamp("1999/09/23")
37
+ assert stamp - offset_no_overflow == expected
38
+
39
+ def test_overflow_offset_raises(self):
40
+ # xref https://github.com/statsmodels/statsmodels/issues/3374
41
+ # ends up multiplying really large numbers which overflow
42
+
43
+ stamp = Timestamp("2017-01-13 00:00:00").as_unit("ns")
44
+ offset_overflow = 20169940 * offsets.Day(1)
45
+ lmsg2 = r"Cannot cast -?20169940 days \+?00:00:00 to unit='ns' without overflow"
46
+
47
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):
48
+ stamp + offset_overflow
49
+
50
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):
51
+ offset_overflow + stamp
52
+
53
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):
54
+ stamp - offset_overflow
55
+
56
+ # xref https://github.com/pandas-dev/pandas/issues/14080
57
+ # used to crash, so check for proper overflow exception
58
+
59
+ stamp = Timestamp("2000/1/1").as_unit("ns")
60
+ offset_overflow = to_offset("D") * 100**5
61
+
62
+ lmsg3 = (
63
+ r"Cannot cast -?10000000000 days \+?00:00:00 to unit='ns' without overflow"
64
+ )
65
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):
66
+ stamp + offset_overflow
67
+
68
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):
69
+ offset_overflow + stamp
70
+
71
+ with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):
72
+ stamp - offset_overflow
73
+
74
+ def test_overflow_timestamp_raises(self):
75
+ # https://github.com/pandas-dev/pandas/issues/31774
76
+ msg = "Result is too large"
77
+ a = Timestamp("2101-01-01 00:00:00").as_unit("ns")
78
+ b = Timestamp("1688-01-01 00:00:00").as_unit("ns")
79
+
80
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
81
+ a - b
82
+
83
+ # but we're OK for timestamp and datetime.datetime
84
+ assert (a - b.to_pydatetime()) == (a.to_pydatetime() - b)
85
+
86
+ def test_delta_preserve_nanos(self):
87
+ val = Timestamp(1337299200000000123)
88
+ result = val + timedelta(1)
89
+ assert result.nanosecond == val.nanosecond
90
+
91
+ def test_rsub_dtscalars(self, tz_naive_fixture):
92
+ # In particular, check that datetime64 - Timestamp works GH#28286
93
+ td = Timedelta(1235345642000)
94
+ ts = Timestamp("2021-01-01", tz=tz_naive_fixture)
95
+ other = ts + td
96
+
97
+ assert other - ts == td
98
+ assert other.to_pydatetime() - ts == td
99
+ if tz_naive_fixture is None:
100
+ assert other.to_datetime64() - ts == td
101
+ else:
102
+ msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
103
+ with pytest.raises(TypeError, match=msg):
104
+ other.to_datetime64() - ts
105
+
106
+ def test_timestamp_sub_datetime(self):
107
+ dt = datetime(2013, 10, 12)
108
+ ts = Timestamp(datetime(2013, 10, 13))
109
+ assert (ts - dt).days == 1
110
+ assert (dt - ts).days == -1
111
+
112
+ def test_subtract_tzaware_datetime(self):
113
+ t1 = Timestamp("2020-10-22T22:00:00+00:00")
114
+ t2 = datetime(2020, 10, 22, 22, tzinfo=timezone.utc)
115
+
116
+ result = t1 - t2
117
+
118
+ assert isinstance(result, Timedelta)
119
+ assert result == Timedelta("0 days")
120
+
121
+ def test_subtract_timestamp_from_different_timezone(self):
122
+ t1 = Timestamp("20130101").tz_localize("US/Eastern")
123
+ t2 = Timestamp("20130101").tz_localize("CET")
124
+
125
+ result = t1 - t2
126
+
127
+ assert isinstance(result, Timedelta)
128
+ assert result == Timedelta("0 days 06:00:00")
129
+
130
+ def test_subtracting_involving_datetime_with_different_tz(self):
131
+ t1 = datetime(2013, 1, 1, tzinfo=timezone(timedelta(hours=-5)))
132
+ t2 = Timestamp("20130101").tz_localize("CET")
133
+
134
+ result = t1 - t2
135
+
136
+ assert isinstance(result, Timedelta)
137
+ assert result == Timedelta("0 days 06:00:00")
138
+
139
+ result = t2 - t1
140
+ assert isinstance(result, Timedelta)
141
+ assert result == Timedelta("-1 days +18:00:00")
142
+
143
+ def test_subtracting_different_timezones(self, tz_aware_fixture):
144
+ t_raw = Timestamp("20130101")
145
+ t_UTC = t_raw.tz_localize("UTC")
146
+ t_diff = t_UTC.tz_convert(tz_aware_fixture) + Timedelta("0 days 05:00:00")
147
+
148
+ result = t_diff - t_UTC
149
+
150
+ assert isinstance(result, Timedelta)
151
+ assert result == Timedelta("0 days 05:00:00")
152
+
153
+ def test_addition_subtraction_types(self):
154
+ # Assert on the types resulting from Timestamp +/- various date/time
155
+ # objects
156
+ dt = datetime(2014, 3, 4)
157
+ td = timedelta(seconds=1)
158
+ ts = Timestamp(dt)
159
+
160
+ msg = "Addition/subtraction of integers"
161
+ with pytest.raises(TypeError, match=msg):
162
+ # GH#22535 add/sub with integers is deprecated
163
+ ts + 1
164
+ with pytest.raises(TypeError, match=msg):
165
+ ts - 1
166
+
167
+ # Timestamp + datetime not supported, though subtraction is supported
168
+ # and yields timedelta more tests in tseries/base/tests/test_base.py
169
+ assert type(ts - dt) == Timedelta
170
+ assert type(ts + td) == Timestamp
171
+ assert type(ts - td) == Timestamp
172
+
173
+ # Timestamp +/- datetime64 not supported, so not tested (could possibly
174
+ # assert error raised?)
175
+ td64 = np.timedelta64(1, "D")
176
+ assert type(ts + td64) == Timestamp
177
+ assert type(ts - td64) == Timestamp
178
+
179
+ @pytest.mark.parametrize(
180
+ "td", [Timedelta(hours=3), np.timedelta64(3, "h"), timedelta(hours=3)]
181
+ )
182
+ def test_radd_tdscalar(self, td, fixed_now_ts):
183
+ # GH#24775 timedelta64+Timestamp should not raise
184
+ ts = fixed_now_ts
185
+ assert td + ts == ts + td
186
+
187
+ @pytest.mark.parametrize(
188
+ "other,expected_difference",
189
+ [
190
+ (np.timedelta64(-123, "ns"), -123),
191
+ (np.timedelta64(1234567898, "ns"), 1234567898),
192
+ (np.timedelta64(-123, "us"), -123000),
193
+ (np.timedelta64(-123, "ms"), -123000000),
194
+ ],
195
+ )
196
+ def test_timestamp_add_timedelta64_unit(self, other, expected_difference):
197
+ now = datetime.now(timezone.utc)
198
+ ts = Timestamp(now).as_unit("ns")
199
+ result = ts + other
200
+ valdiff = result._value - ts._value
201
+ assert valdiff == expected_difference
202
+
203
+ ts2 = Timestamp(now)
204
+ assert ts2 + other == result
205
+
206
+ @pytest.mark.parametrize(
207
+ "ts",
208
+ [
209
+ Timestamp("1776-07-04"),
210
+ Timestamp("1776-07-04", tz="UTC"),
211
+ ],
212
+ )
213
+ @pytest.mark.parametrize(
214
+ "other",
215
+ [
216
+ 1,
217
+ np.int64(1),
218
+ np.array([1, 2], dtype=np.int32),
219
+ np.array([3, 4], dtype=np.uint64),
220
+ ],
221
+ )
222
+ def test_add_int_with_freq(self, ts, other):
223
+ msg = "Addition/subtraction of integers and integer-arrays"
224
+ with pytest.raises(TypeError, match=msg):
225
+ ts + other
226
+ with pytest.raises(TypeError, match=msg):
227
+ other + ts
228
+
229
+ with pytest.raises(TypeError, match=msg):
230
+ ts - other
231
+
232
+ msg = "unsupported operand type"
233
+ with pytest.raises(TypeError, match=msg):
234
+ other - ts
235
+
236
+ @pytest.mark.parametrize("shape", [(6,), (2, 3)])
237
+ def test_addsub_m8ndarray(self, shape):
238
+ # GH#33296
239
+ ts = Timestamp("2020-04-04 15:45").as_unit("ns")
240
+ other = np.arange(6).astype("m8[h]").reshape(shape)
241
+
242
+ result = ts + other
243
+
244
+ ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]
245
+ expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)
246
+ tm.assert_numpy_array_equal(result, expected)
247
+
248
+ result = other + ts
249
+ tm.assert_numpy_array_equal(result, expected)
250
+
251
+ result = ts - other
252
+ ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]
253
+ expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)
254
+ tm.assert_numpy_array_equal(result, expected)
255
+
256
+ msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"
257
+ with pytest.raises(TypeError, match=msg):
258
+ other - ts
259
+
260
+ @pytest.mark.parametrize("shape", [(6,), (2, 3)])
261
+ def test_addsub_m8ndarray_tzaware(self, shape):
262
+ # GH#33296
263
+ ts = Timestamp("2020-04-04 15:45", tz="US/Pacific")
264
+
265
+ other = np.arange(6).astype("m8[h]").reshape(shape)
266
+
267
+ result = ts + other
268
+
269
+ ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]
270
+ expected = np.array(ex_stamps).reshape(shape)
271
+ tm.assert_numpy_array_equal(result, expected)
272
+
273
+ result = other + ts
274
+ tm.assert_numpy_array_equal(result, expected)
275
+
276
+ result = ts - other
277
+ ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]
278
+ expected = np.array(ex_stamps).reshape(shape)
279
+ tm.assert_numpy_array_equal(result, expected)
280
+
281
+ msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"
282
+ with pytest.raises(TypeError, match=msg):
283
+ other - ts
284
+
285
+ def test_subtract_different_utc_objects(self, utc_fixture, utc_fixture2):
286
+ # GH 32619
287
+ dt = datetime(2021, 1, 1)
288
+ ts1 = Timestamp(dt, tz=utc_fixture)
289
+ ts2 = Timestamp(dt, tz=utc_fixture2)
290
+ result = ts1 - ts2
291
+ expected = Timedelta(0)
292
+ assert result == expected
293
+
294
+ @pytest.mark.parametrize(
295
+ "tz",
296
+ [
297
+ pytz.timezone("US/Eastern"),
298
+ gettz("US/Eastern"),
299
+ "US/Eastern",
300
+ "dateutil/US/Eastern",
301
+ ],
302
+ )
303
+ def test_timestamp_add_timedelta_push_over_dst_boundary(self, tz):
304
+ # GH#1389
305
+
306
+ # 4 hours before DST transition
307
+ stamp = Timestamp("3/10/2012 22:00", tz=tz)
308
+
309
+ result = stamp + timedelta(hours=6)
310
+
311
+ # spring forward, + "7" hours
312
+ expected = Timestamp("3/11/2012 05:00", tz=tz)
313
+
314
+ assert result == expected
315
+
316
+
317
+ class SubDatetime(datetime):
318
+ pass
319
+
320
+
321
+ @pytest.mark.parametrize(
322
+ "lh,rh",
323
+ [
324
+ (SubDatetime(2000, 1, 1), Timedelta(hours=1)),
325
+ (Timedelta(hours=1), SubDatetime(2000, 1, 1)),
326
+ ],
327
+ )
328
+ def test_dt_subclass_add_timedelta(lh, rh):
329
+ # GH#25851
330
+ # ensure that subclassed datetime works for
331
+ # Timedelta operations
332
+ result = lh + rh
333
+ expected = SubDatetime(2000, 1, 1, 1)
334
+ assert result == expected
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_comparisons.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+ import operator
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from pandas import Timestamp
11
+ import pandas._testing as tm
12
+
13
+
14
+ class TestTimestampComparison:
15
+ def test_compare_non_nano_dt64(self):
16
+ # don't raise when converting dt64 to Timestamp in __richcmp__
17
+ dt = np.datetime64("1066-10-14")
18
+ ts = Timestamp(dt)
19
+
20
+ assert dt == ts
21
+
22
+ def test_comparison_dt64_ndarray(self):
23
+ ts = Timestamp("2021-01-01")
24
+ ts2 = Timestamp("2019-04-05")
25
+ arr = np.array([[ts.asm8, ts2.asm8]], dtype="M8[ns]")
26
+
27
+ result = ts == arr
28
+ expected = np.array([[True, False]], dtype=bool)
29
+ tm.assert_numpy_array_equal(result, expected)
30
+
31
+ result = arr == ts
32
+ tm.assert_numpy_array_equal(result, expected)
33
+
34
+ result = ts != arr
35
+ tm.assert_numpy_array_equal(result, ~expected)
36
+
37
+ result = arr != ts
38
+ tm.assert_numpy_array_equal(result, ~expected)
39
+
40
+ result = ts2 < arr
41
+ tm.assert_numpy_array_equal(result, expected)
42
+
43
+ result = arr < ts2
44
+ tm.assert_numpy_array_equal(result, np.array([[False, False]], dtype=bool))
45
+
46
+ result = ts2 <= arr
47
+ tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))
48
+
49
+ result = arr <= ts2
50
+ tm.assert_numpy_array_equal(result, ~expected)
51
+
52
+ result = ts >= arr
53
+ tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))
54
+
55
+ result = arr >= ts
56
+ tm.assert_numpy_array_equal(result, np.array([[True, False]], dtype=bool))
57
+
58
+ @pytest.mark.parametrize("reverse", [True, False])
59
+ def test_comparison_dt64_ndarray_tzaware(self, reverse, comparison_op):
60
+ ts = Timestamp("2021-01-01 00:00:00.00000", tz="UTC")
61
+ arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]")
62
+
63
+ left, right = ts, arr
64
+ if reverse:
65
+ left, right = arr, ts
66
+
67
+ if comparison_op is operator.eq:
68
+ expected = np.array([False, False], dtype=bool)
69
+ result = comparison_op(left, right)
70
+ tm.assert_numpy_array_equal(result, expected)
71
+ elif comparison_op is operator.ne:
72
+ expected = np.array([True, True], dtype=bool)
73
+ result = comparison_op(left, right)
74
+ tm.assert_numpy_array_equal(result, expected)
75
+ else:
76
+ msg = "Cannot compare tz-naive and tz-aware timestamps"
77
+ with pytest.raises(TypeError, match=msg):
78
+ comparison_op(left, right)
79
+
80
+ def test_comparison_object_array(self):
81
+ # GH#15183
82
+ ts = Timestamp("2011-01-03 00:00:00-0500", tz="US/Eastern")
83
+ other = Timestamp("2011-01-01 00:00:00-0500", tz="US/Eastern")
84
+ naive = Timestamp("2011-01-01 00:00:00")
85
+
86
+ arr = np.array([other, ts], dtype=object)
87
+ res = arr == ts
88
+ expected = np.array([False, True], dtype=bool)
89
+ assert (res == expected).all()
90
+
91
+ # 2D case
92
+ arr = np.array([[other, ts], [ts, other]], dtype=object)
93
+ res = arr != ts
94
+ expected = np.array([[True, False], [False, True]], dtype=bool)
95
+ assert res.shape == expected.shape
96
+ assert (res == expected).all()
97
+
98
+ # tzaware mismatch
99
+ arr = np.array([naive], dtype=object)
100
+ msg = "Cannot compare tz-naive and tz-aware timestamps"
101
+ with pytest.raises(TypeError, match=msg):
102
+ arr < ts
103
+
104
+ def test_comparison(self):
105
+ # 5-18-2012 00:00:00.000
106
+ stamp = 1337299200000000000
107
+
108
+ val = Timestamp(stamp)
109
+
110
+ assert val == val
111
+ assert not val != val
112
+ assert not val < val
113
+ assert val <= val
114
+ assert not val > val
115
+ assert val >= val
116
+
117
+ other = datetime(2012, 5, 18)
118
+ assert val == other
119
+ assert not val != other
120
+ assert not val < other
121
+ assert val <= other
122
+ assert not val > other
123
+ assert val >= other
124
+
125
+ other = Timestamp(stamp + 100)
126
+
127
+ assert val != other
128
+ assert val != other
129
+ assert val < other
130
+ assert val <= other
131
+ assert other > val
132
+ assert other >= val
133
+
134
+ def test_compare_invalid(self):
135
+ # GH#8058
136
+ val = Timestamp("20130101 12:01:02")
137
+ assert not val == "foo"
138
+ assert not val == 10.0
139
+ assert not val == 1
140
+ assert not val == []
141
+ assert not val == {"foo": 1}
142
+ assert not val == np.float64(1)
143
+ assert not val == np.int64(1)
144
+
145
+ assert val != "foo"
146
+ assert val != 10.0
147
+ assert val != 1
148
+ assert val != []
149
+ assert val != {"foo": 1}
150
+ assert val != np.float64(1)
151
+ assert val != np.int64(1)
152
+
153
+ @pytest.mark.parametrize("tz", [None, "US/Pacific"])
154
+ def test_compare_date(self, tz):
155
+ # GH#36131 comparing Timestamp with date object is deprecated
156
+ ts = Timestamp("2021-01-01 00:00:00.00000", tz=tz)
157
+ dt = ts.to_pydatetime().date()
158
+ # in 2.0 we disallow comparing pydate objects with Timestamps,
159
+ # following the stdlib datetime behavior.
160
+
161
+ msg = "Cannot compare Timestamp with datetime.date"
162
+ for left, right in [(ts, dt), (dt, ts)]:
163
+ assert not left == right
164
+ assert left != right
165
+
166
+ with pytest.raises(TypeError, match=msg):
167
+ left < right
168
+ with pytest.raises(TypeError, match=msg):
169
+ left <= right
170
+ with pytest.raises(TypeError, match=msg):
171
+ left > right
172
+ with pytest.raises(TypeError, match=msg):
173
+ left >= right
174
+
175
+ def test_cant_compare_tz_naive_w_aware(self, utc_fixture):
176
+ # see GH#1404
177
+ a = Timestamp("3/12/2012")
178
+ b = Timestamp("3/12/2012", tz=utc_fixture)
179
+
180
+ msg = "Cannot compare tz-naive and tz-aware timestamps"
181
+ assert not a == b
182
+ assert a != b
183
+ with pytest.raises(TypeError, match=msg):
184
+ a < b
185
+ with pytest.raises(TypeError, match=msg):
186
+ a <= b
187
+ with pytest.raises(TypeError, match=msg):
188
+ a > b
189
+ with pytest.raises(TypeError, match=msg):
190
+ a >= b
191
+
192
+ assert not b == a
193
+ assert b != a
194
+ with pytest.raises(TypeError, match=msg):
195
+ b < a
196
+ with pytest.raises(TypeError, match=msg):
197
+ b <= a
198
+ with pytest.raises(TypeError, match=msg):
199
+ b > a
200
+ with pytest.raises(TypeError, match=msg):
201
+ b >= a
202
+
203
+ assert not a == b.to_pydatetime()
204
+ assert not a.to_pydatetime() == b
205
+
206
+ def test_timestamp_compare_scalars(self):
207
+ # case where ndim == 0
208
+ lhs = np.datetime64(datetime(2013, 12, 6))
209
+ rhs = Timestamp("now")
210
+ nat = Timestamp("nat")
211
+
212
+ ops = {"gt": "lt", "lt": "gt", "ge": "le", "le": "ge", "eq": "eq", "ne": "ne"}
213
+
214
+ for left, right in ops.items():
215
+ left_f = getattr(operator, left)
216
+ right_f = getattr(operator, right)
217
+ expected = left_f(lhs, rhs)
218
+
219
+ result = right_f(rhs, lhs)
220
+ assert result == expected
221
+
222
+ expected = left_f(rhs, nat)
223
+ result = right_f(nat, rhs)
224
+ assert result == expected
225
+
226
+ def test_timestamp_compare_with_early_datetime(self):
227
+ # e.g. datetime.min
228
+ stamp = Timestamp("2012-01-01")
229
+
230
+ assert not stamp == datetime.min
231
+ assert not stamp == datetime(1600, 1, 1)
232
+ assert not stamp == datetime(2700, 1, 1)
233
+ assert stamp != datetime.min
234
+ assert stamp != datetime(1600, 1, 1)
235
+ assert stamp != datetime(2700, 1, 1)
236
+ assert stamp > datetime(1600, 1, 1)
237
+ assert stamp >= datetime(1600, 1, 1)
238
+ assert stamp < datetime(2700, 1, 1)
239
+ assert stamp <= datetime(2700, 1, 1)
240
+
241
+ other = Timestamp.min.to_pydatetime(warn=False)
242
+ assert other - timedelta(microseconds=1) < Timestamp.min
243
+
244
+ def test_timestamp_compare_oob_dt64(self):
245
+ us = np.timedelta64(1, "us")
246
+ other = np.datetime64(Timestamp.min).astype("M8[us]")
247
+
248
+ # This may change if the implementation bound is dropped to match
249
+ # DatetimeArray/DatetimeIndex GH#24124
250
+ assert Timestamp.min > other
251
+ # Note: numpy gets the reversed comparison wrong
252
+
253
+ other = np.datetime64(Timestamp.max).astype("M8[us]")
254
+ assert Timestamp.max > other # not actually OOB
255
+ assert other < Timestamp.max
256
+
257
+ assert Timestamp.max < other + us
258
+ # Note: numpy gets the reversed comparison wrong
259
+
260
+ # GH-42794
261
+ other = datetime(9999, 9, 9)
262
+ assert Timestamp.min < other
263
+ assert other > Timestamp.min
264
+ assert Timestamp.max < other
265
+ assert other > Timestamp.max
266
+
267
+ other = datetime(1, 1, 1)
268
+ assert Timestamp.max > other
269
+ assert other < Timestamp.max
270
+ assert Timestamp.min > other
271
+ assert other < Timestamp.min
272
+
273
+ def test_compare_zerodim_array(self, fixed_now_ts):
274
+ # GH#26916
275
+ ts = fixed_now_ts
276
+ dt64 = np.datetime64("2016-01-01", "ns")
277
+ arr = np.array(dt64)
278
+ assert arr.ndim == 0
279
+
280
+ result = arr < ts
281
+ assert result is np.bool_(True)
282
+ result = arr > ts
283
+ assert result is np.bool_(False)
284
+
285
+
286
+ def test_rich_comparison_with_unsupported_type():
287
+ # Comparisons with unsupported objects should return NotImplemented
288
+ # (it previously raised TypeError, see #24011)
289
+
290
+ class Inf:
291
+ def __lt__(self, o):
292
+ return False
293
+
294
+ def __le__(self, o):
295
+ return isinstance(o, Inf)
296
+
297
+ def __gt__(self, o):
298
+ return not isinstance(o, Inf)
299
+
300
+ def __ge__(self, o):
301
+ return True
302
+
303
+ def __eq__(self, other) -> bool:
304
+ return isinstance(other, Inf)
305
+
306
+ inf = Inf()
307
+ timestamp = Timestamp("2018-11-30")
308
+
309
+ for left, right in [(inf, timestamp), (timestamp, inf)]:
310
+ assert left > right or left < right
311
+ assert left >= right or left <= right
312
+ assert not left == right # pylint: disable=unneeded-not
313
+ assert left != right
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_constructors.py ADDED
@@ -0,0 +1,1068 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import calendar
2
+ from datetime import (
3
+ date,
4
+ datetime,
5
+ timedelta,
6
+ timezone,
7
+ )
8
+ import zoneinfo
9
+
10
+ import dateutil.tz
11
+ from dateutil.tz import (
12
+ gettz,
13
+ tzoffset,
14
+ tzutc,
15
+ )
16
+ import numpy as np
17
+ import pytest
18
+ import pytz
19
+
20
+ from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
21
+ from pandas.compat import PY310
22
+ from pandas.errors import OutOfBoundsDatetime
23
+
24
+ from pandas import (
25
+ NA,
26
+ NaT,
27
+ Period,
28
+ Timedelta,
29
+ Timestamp,
30
+ )
31
+
32
+
33
+ class TestTimestampConstructorUnitKeyword:
34
+ @pytest.mark.parametrize("typ", [int, float])
35
+ def test_constructor_int_float_with_YM_unit(self, typ):
36
+ # GH#47266 avoid the conversions in cast_from_unit
37
+ val = typ(150)
38
+
39
+ ts = Timestamp(val, unit="Y")
40
+ expected = Timestamp("2120-01-01")
41
+ assert ts == expected
42
+
43
+ ts = Timestamp(val, unit="M")
44
+ expected = Timestamp("1982-07-01")
45
+ assert ts == expected
46
+
47
+ @pytest.mark.parametrize("typ", [int, float])
48
+ def test_construct_from_int_float_with_unit_out_of_bound_raises(self, typ):
49
+ # GH#50870 make sure we get a OutOfBoundsDatetime instead of OverflowError
50
+ val = typ(150000000000000)
51
+
52
+ msg = f"cannot convert input {val} with the unit 'D'"
53
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
54
+ Timestamp(val, unit="D")
55
+
56
+ def test_constructor_float_not_round_with_YM_unit_raises(self):
57
+ # GH#47267 avoid the conversions in cast_from-unit
58
+
59
+ msg = "Conversion of non-round float with unit=[MY] is ambiguous"
60
+ with pytest.raises(ValueError, match=msg):
61
+ Timestamp(150.5, unit="Y")
62
+
63
+ with pytest.raises(ValueError, match=msg):
64
+ Timestamp(150.5, unit="M")
65
+
66
+ @pytest.mark.parametrize(
67
+ "value, check_kwargs",
68
+ [
69
+ [946688461000000000, {}],
70
+ [946688461000000000 / 1000, {"unit": "us"}],
71
+ [946688461000000000 / 1_000_000, {"unit": "ms"}],
72
+ [946688461000000000 / 1_000_000_000, {"unit": "s"}],
73
+ [10957, {"unit": "D", "h": 0}],
74
+ [
75
+ (946688461000000000 + 500000) / 1000000000,
76
+ {"unit": "s", "us": 499, "ns": 964},
77
+ ],
78
+ [
79
+ (946688461000000000 + 500000000) / 1000000000,
80
+ {"unit": "s", "us": 500000},
81
+ ],
82
+ [(946688461000000000 + 500000) / 1000000, {"unit": "ms", "us": 500}],
83
+ [(946688461000000000 + 500000) / 1000, {"unit": "us", "us": 500}],
84
+ [(946688461000000000 + 500000000) / 1000000, {"unit": "ms", "us": 500000}],
85
+ [946688461000000000 / 1000.0 + 5, {"unit": "us", "us": 5}],
86
+ [946688461000000000 / 1000.0 + 5000, {"unit": "us", "us": 5000}],
87
+ [946688461000000000 / 1000000.0 + 0.5, {"unit": "ms", "us": 500}],
88
+ [946688461000000000 / 1000000.0 + 0.005, {"unit": "ms", "us": 5, "ns": 5}],
89
+ [946688461000000000 / 1000000000.0 + 0.5, {"unit": "s", "us": 500000}],
90
+ [10957 + 0.5, {"unit": "D", "h": 12}],
91
+ ],
92
+ )
93
+ def test_construct_with_unit(self, value, check_kwargs):
94
+ def check(value, unit=None, h=1, s=1, us=0, ns=0):
95
+ stamp = Timestamp(value, unit=unit)
96
+ assert stamp.year == 2000
97
+ assert stamp.month == 1
98
+ assert stamp.day == 1
99
+ assert stamp.hour == h
100
+ if unit != "D":
101
+ assert stamp.minute == 1
102
+ assert stamp.second == s
103
+ assert stamp.microsecond == us
104
+ else:
105
+ assert stamp.minute == 0
106
+ assert stamp.second == 0
107
+ assert stamp.microsecond == 0
108
+ assert stamp.nanosecond == ns
109
+
110
+ check(value, **check_kwargs)
111
+
112
+
113
+ class TestTimestampConstructorFoldKeyword:
114
+ def test_timestamp_constructor_invalid_fold_raise(self):
115
+ # Test for GH#25057
116
+ # Valid fold values are only [None, 0, 1]
117
+ msg = "Valid values for the fold argument are None, 0, or 1."
118
+ with pytest.raises(ValueError, match=msg):
119
+ Timestamp(123, fold=2)
120
+
121
+ def test_timestamp_constructor_pytz_fold_raise(self):
122
+ # Test for GH#25057
123
+ # pytz doesn't support fold. Check that we raise
124
+ # if fold is passed with pytz
125
+ msg = "pytz timezones do not support fold. Please use dateutil timezones."
126
+ tz = pytz.timezone("Europe/London")
127
+ with pytest.raises(ValueError, match=msg):
128
+ Timestamp(datetime(2019, 10, 27, 0, 30, 0, 0), tz=tz, fold=0)
129
+
130
+ @pytest.mark.parametrize("fold", [0, 1])
131
+ @pytest.mark.parametrize(
132
+ "ts_input",
133
+ [
134
+ 1572136200000000000,
135
+ 1572136200000000000.0,
136
+ np.datetime64(1572136200000000000, "ns"),
137
+ "2019-10-27 01:30:00+01:00",
138
+ datetime(2019, 10, 27, 0, 30, 0, 0, tzinfo=timezone.utc),
139
+ ],
140
+ )
141
+ def test_timestamp_constructor_fold_conflict(self, ts_input, fold):
142
+ # Test for GH#25057
143
+ # Check that we raise on fold conflict
144
+ msg = (
145
+ "Cannot pass fold with possibly unambiguous input: int, float, "
146
+ "numpy.datetime64, str, or timezone-aware datetime-like. "
147
+ "Pass naive datetime-like or build Timestamp from components."
148
+ )
149
+ with pytest.raises(ValueError, match=msg):
150
+ Timestamp(ts_input=ts_input, fold=fold)
151
+
152
+ @pytest.mark.parametrize("tz", ["dateutil/Europe/London", None])
153
+ @pytest.mark.parametrize("fold", [0, 1])
154
+ def test_timestamp_constructor_retain_fold(self, tz, fold):
155
+ # Test for GH#25057
156
+ # Check that we retain fold
157
+ ts = Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold)
158
+ result = ts.fold
159
+ expected = fold
160
+ assert result == expected
161
+
162
+ try:
163
+ _tzs = [
164
+ "dateutil/Europe/London",
165
+ zoneinfo.ZoneInfo("Europe/London"),
166
+ ]
167
+ except zoneinfo.ZoneInfoNotFoundError:
168
+ _tzs = ["dateutil/Europe/London"]
169
+
170
+ @pytest.mark.parametrize("tz", _tzs)
171
+ @pytest.mark.parametrize(
172
+ "ts_input,fold_out",
173
+ [
174
+ (1572136200000000000, 0),
175
+ (1572139800000000000, 1),
176
+ ("2019-10-27 01:30:00+01:00", 0),
177
+ ("2019-10-27 01:30:00+00:00", 1),
178
+ (datetime(2019, 10, 27, 1, 30, 0, 0, fold=0), 0),
179
+ (datetime(2019, 10, 27, 1, 30, 0, 0, fold=1), 1),
180
+ ],
181
+ )
182
+ def test_timestamp_constructor_infer_fold_from_value(self, tz, ts_input, fold_out):
183
+ # Test for GH#25057
184
+ # Check that we infer fold correctly based on timestamps since utc
185
+ # or strings
186
+ ts = Timestamp(ts_input, tz=tz)
187
+ result = ts.fold
188
+ expected = fold_out
189
+ assert result == expected
190
+
191
+ @pytest.mark.parametrize("tz", ["dateutil/Europe/London"])
192
+ @pytest.mark.parametrize(
193
+ "ts_input,fold,value_out",
194
+ [
195
+ (datetime(2019, 10, 27, 1, 30, 0, 0), 0, 1572136200000000),
196
+ (datetime(2019, 10, 27, 1, 30, 0, 0), 1, 1572139800000000),
197
+ ],
198
+ )
199
+ def test_timestamp_constructor_adjust_value_for_fold(
200
+ self, tz, ts_input, fold, value_out
201
+ ):
202
+ # Test for GH#25057
203
+ # Check that we adjust value for fold correctly
204
+ # based on timestamps since utc
205
+ ts = Timestamp(ts_input, tz=tz, fold=fold)
206
+ result = ts._value
207
+ expected = value_out
208
+ assert result == expected
209
+
210
+
211
+ class TestTimestampConstructorPositionalAndKeywordSupport:
212
+ def test_constructor_positional(self):
213
+ # see GH#10758
214
+ msg = (
215
+ "'NoneType' object cannot be interpreted as an integer"
216
+ if PY310
217
+ else "an integer is required"
218
+ )
219
+ with pytest.raises(TypeError, match=msg):
220
+ Timestamp(2000, 1)
221
+
222
+ msg = "month must be in 1..12"
223
+ with pytest.raises(ValueError, match=msg):
224
+ Timestamp(2000, 0, 1)
225
+ with pytest.raises(ValueError, match=msg):
226
+ Timestamp(2000, 13, 1)
227
+
228
+ msg = "day is out of range for month"
229
+ with pytest.raises(ValueError, match=msg):
230
+ Timestamp(2000, 1, 0)
231
+ with pytest.raises(ValueError, match=msg):
232
+ Timestamp(2000, 1, 32)
233
+
234
+ # see gh-11630
235
+ assert repr(Timestamp(2015, 11, 12)) == repr(Timestamp("20151112"))
236
+ assert repr(Timestamp(2015, 11, 12, 1, 2, 3, 999999)) == repr(
237
+ Timestamp("2015-11-12 01:02:03.999999")
238
+ )
239
+
240
+ def test_constructor_keyword(self):
241
+ # GH#10758
242
+ msg = "function missing required argument 'day'|Required argument 'day'"
243
+ with pytest.raises(TypeError, match=msg):
244
+ Timestamp(year=2000, month=1)
245
+
246
+ msg = "month must be in 1..12"
247
+ with pytest.raises(ValueError, match=msg):
248
+ Timestamp(year=2000, month=0, day=1)
249
+ with pytest.raises(ValueError, match=msg):
250
+ Timestamp(year=2000, month=13, day=1)
251
+
252
+ msg = "day is out of range for month"
253
+ with pytest.raises(ValueError, match=msg):
254
+ Timestamp(year=2000, month=1, day=0)
255
+ with pytest.raises(ValueError, match=msg):
256
+ Timestamp(year=2000, month=1, day=32)
257
+
258
+ assert repr(Timestamp(year=2015, month=11, day=12)) == repr(
259
+ Timestamp("20151112")
260
+ )
261
+
262
+ assert repr(
263
+ Timestamp(
264
+ year=2015,
265
+ month=11,
266
+ day=12,
267
+ hour=1,
268
+ minute=2,
269
+ second=3,
270
+ microsecond=999999,
271
+ )
272
+ ) == repr(Timestamp("2015-11-12 01:02:03.999999"))
273
+
274
+ @pytest.mark.parametrize(
275
+ "arg",
276
+ [
277
+ "year",
278
+ "month",
279
+ "day",
280
+ "hour",
281
+ "minute",
282
+ "second",
283
+ "microsecond",
284
+ "nanosecond",
285
+ ],
286
+ )
287
+ def test_invalid_date_kwarg_with_string_input(self, arg):
288
+ kwarg = {arg: 1}
289
+ msg = "Cannot pass a date attribute keyword argument"
290
+ with pytest.raises(ValueError, match=msg):
291
+ Timestamp("2010-10-10 12:59:59.999999999", **kwarg)
292
+
293
+ @pytest.mark.parametrize("kwargs", [{}, {"year": 2020}, {"year": 2020, "month": 1}])
294
+ def test_constructor_missing_keyword(self, kwargs):
295
+ # GH#31200
296
+
297
+ # The exact error message of datetime() depends on its version
298
+ msg1 = r"function missing required argument '(year|month|day)' \(pos [123]\)"
299
+ msg2 = r"Required argument '(year|month|day)' \(pos [123]\) not found"
300
+ msg = "|".join([msg1, msg2])
301
+
302
+ with pytest.raises(TypeError, match=msg):
303
+ Timestamp(**kwargs)
304
+
305
+ def test_constructor_positional_with_tzinfo(self):
306
+ # GH#31929
307
+ ts = Timestamp(2020, 12, 31, tzinfo=timezone.utc)
308
+ expected = Timestamp("2020-12-31", tzinfo=timezone.utc)
309
+ assert ts == expected
310
+
311
+ @pytest.mark.parametrize("kwd", ["nanosecond", "microsecond", "second", "minute"])
312
+ def test_constructor_positional_keyword_mixed_with_tzinfo(self, kwd, request):
313
+ # TODO: if we passed microsecond with a keyword we would mess up
314
+ # xref GH#45307
315
+ if kwd != "nanosecond":
316
+ # nanosecond is keyword-only as of 2.0, others are not
317
+ mark = pytest.mark.xfail(reason="GH#45307")
318
+ request.applymarker(mark)
319
+
320
+ kwargs = {kwd: 4}
321
+ ts = Timestamp(2020, 12, 31, tzinfo=timezone.utc, **kwargs)
322
+
323
+ td_kwargs = {kwd + "s": 4}
324
+ td = Timedelta(**td_kwargs)
325
+ expected = Timestamp("2020-12-31", tz=timezone.utc) + td
326
+ assert ts == expected
327
+
328
+
329
+ class TestTimestampClassMethodConstructors:
330
+ # Timestamp constructors other than __new__
331
+
332
+ def test_constructor_strptime(self):
333
+ # GH#25016
334
+ # Test support for Timestamp.strptime
335
+ fmt = "%Y%m%d-%H%M%S-%f%z"
336
+ ts = "20190129-235348-000001+0000"
337
+ msg = r"Timestamp.strptime\(\) is not implemented"
338
+ with pytest.raises(NotImplementedError, match=msg):
339
+ Timestamp.strptime(ts, fmt)
340
+
341
+ def test_constructor_fromisocalendar(self):
342
+ # GH#30395
343
+ expected_timestamp = Timestamp("2000-01-03 00:00:00")
344
+ expected_stdlib = datetime.fromisocalendar(2000, 1, 1)
345
+ result = Timestamp.fromisocalendar(2000, 1, 1)
346
+ assert result == expected_timestamp
347
+ assert result == expected_stdlib
348
+ assert isinstance(result, Timestamp)
349
+
350
+ def test_constructor_fromordinal(self):
351
+ base = datetime(2000, 1, 1)
352
+
353
+ ts = Timestamp.fromordinal(base.toordinal())
354
+ assert base == ts
355
+ assert base.toordinal() == ts.toordinal()
356
+
357
+ ts = Timestamp.fromordinal(base.toordinal(), tz="US/Eastern")
358
+ assert Timestamp("2000-01-01", tz="US/Eastern") == ts
359
+ assert base.toordinal() == ts.toordinal()
360
+
361
+ # GH#3042
362
+ dt = datetime(2011, 4, 16, 0, 0)
363
+ ts = Timestamp.fromordinal(dt.toordinal())
364
+ assert ts.to_pydatetime() == dt
365
+
366
+ # with a tzinfo
367
+ stamp = Timestamp("2011-4-16", tz="US/Eastern")
368
+ dt_tz = stamp.to_pydatetime()
369
+ ts = Timestamp.fromordinal(dt_tz.toordinal(), tz="US/Eastern")
370
+ assert ts.to_pydatetime() == dt_tz
371
+
372
+ def test_now(self):
373
+ # GH#9000
374
+ ts_from_string = Timestamp("now")
375
+ ts_from_method = Timestamp.now()
376
+ ts_datetime = datetime.now()
377
+
378
+ ts_from_string_tz = Timestamp("now", tz="US/Eastern")
379
+ ts_from_method_tz = Timestamp.now(tz="US/Eastern")
380
+
381
+ # Check that the delta between the times is less than 1s (arbitrarily
382
+ # small)
383
+ delta = Timedelta(seconds=1)
384
+ assert abs(ts_from_method - ts_from_string) < delta
385
+ assert abs(ts_datetime - ts_from_method) < delta
386
+ assert abs(ts_from_method_tz - ts_from_string_tz) < delta
387
+ assert (
388
+ abs(
389
+ ts_from_string_tz.tz_localize(None)
390
+ - ts_from_method_tz.tz_localize(None)
391
+ )
392
+ < delta
393
+ )
394
+
395
+ def test_today(self):
396
+ ts_from_string = Timestamp("today")
397
+ ts_from_method = Timestamp.today()
398
+ ts_datetime = datetime.today()
399
+
400
+ ts_from_string_tz = Timestamp("today", tz="US/Eastern")
401
+ ts_from_method_tz = Timestamp.today(tz="US/Eastern")
402
+
403
+ # Check that the delta between the times is less than 1s (arbitrarily
404
+ # small)
405
+ delta = Timedelta(seconds=1)
406
+ assert abs(ts_from_method - ts_from_string) < delta
407
+ assert abs(ts_datetime - ts_from_method) < delta
408
+ assert abs(ts_from_method_tz - ts_from_string_tz) < delta
409
+ assert (
410
+ abs(
411
+ ts_from_string_tz.tz_localize(None)
412
+ - ts_from_method_tz.tz_localize(None)
413
+ )
414
+ < delta
415
+ )
416
+
417
+
418
+ class TestTimestampResolutionInference:
419
+ def test_construct_from_time_unit(self):
420
+ # GH#54097 only passing a time component, no date
421
+ ts = Timestamp("01:01:01.111")
422
+ assert ts.unit == "ms"
423
+
424
+ def test_constructor_str_infer_reso(self):
425
+ # non-iso8601 path
426
+
427
+ # _parse_delimited_date path
428
+ ts = Timestamp("01/30/2023")
429
+ assert ts.unit == "s"
430
+
431
+ # _parse_dateabbr_string path
432
+ ts = Timestamp("2015Q1")
433
+ assert ts.unit == "s"
434
+
435
+ # dateutil_parse path
436
+ ts = Timestamp("2016-01-01 1:30:01 PM")
437
+ assert ts.unit == "s"
438
+
439
+ ts = Timestamp("2016 June 3 15:25:01.345")
440
+ assert ts.unit == "ms"
441
+
442
+ ts = Timestamp("300-01-01")
443
+ assert ts.unit == "s"
444
+
445
+ ts = Timestamp("300 June 1:30:01.300")
446
+ assert ts.unit == "ms"
447
+
448
+ # dateutil path -> don't drop trailing zeros
449
+ ts = Timestamp("01-01-2013T00:00:00.000000000+0000")
450
+ assert ts.unit == "ns"
451
+
452
+ ts = Timestamp("2016/01/02 03:04:05.001000 UTC")
453
+ assert ts.unit == "us"
454
+
455
+ # higher-than-nanosecond -> we drop the trailing bits
456
+ ts = Timestamp("01-01-2013T00:00:00.000000002100+0000")
457
+ assert ts == Timestamp("01-01-2013T00:00:00.000000002+0000")
458
+ assert ts.unit == "ns"
459
+
460
+ # GH#56208 minute reso through the ISO8601 path with tz offset
461
+ ts = Timestamp("2020-01-01 00:00+00:00")
462
+ assert ts.unit == "s"
463
+
464
+ ts = Timestamp("2020-01-01 00+00:00")
465
+ assert ts.unit == "s"
466
+
467
+ @pytest.mark.parametrize("method", ["now", "today"])
468
+ def test_now_today_unit(self, method):
469
+ # GH#55879
470
+ ts_from_method = getattr(Timestamp, method)()
471
+ ts_from_string = Timestamp(method)
472
+ assert ts_from_method.unit == ts_from_string.unit == "us"
473
+
474
+
475
+ class TestTimestampConstructors:
476
+ def test_weekday_but_no_day_raises(self):
477
+ # GH#52659
478
+ msg = "Parsing datetimes with weekday but no day information is not supported"
479
+ with pytest.raises(ValueError, match=msg):
480
+ Timestamp("2023 Sept Thu")
481
+
482
+ def test_construct_from_string_invalid_raises(self):
483
+ # dateutil (weirdly) parses "200622-12-31" as
484
+ # datetime(2022, 6, 20, 12, 0, tzinfo=tzoffset(None, -111600)
485
+ # which besides being mis-parsed, is a tzoffset that will cause
486
+ # str(ts) to raise ValueError. Ensure we raise in the constructor
487
+ # instead.
488
+ # see test_to_datetime_malformed_raise for analogous to_datetime test
489
+ with pytest.raises(ValueError, match="gives an invalid tzoffset"):
490
+ Timestamp("200622-12-31")
491
+
492
+ def test_constructor_from_iso8601_str_with_offset_reso(self):
493
+ # GH#49737
494
+ ts = Timestamp("2016-01-01 04:05:06-01:00")
495
+ assert ts.unit == "s"
496
+
497
+ ts = Timestamp("2016-01-01 04:05:06.000-01:00")
498
+ assert ts.unit == "ms"
499
+
500
+ ts = Timestamp("2016-01-01 04:05:06.000000-01:00")
501
+ assert ts.unit == "us"
502
+
503
+ ts = Timestamp("2016-01-01 04:05:06.000000001-01:00")
504
+ assert ts.unit == "ns"
505
+
506
+ def test_constructor_from_date_second_reso(self):
507
+ # GH#49034 constructing from a pydate object gets lowest supported
508
+ # reso, i.e. seconds
509
+ obj = date(2012, 9, 1)
510
+ ts = Timestamp(obj)
511
+ assert ts.unit == "s"
512
+
513
+ def test_constructor_datetime64_with_tz(self):
514
+ # GH#42288, GH#24559
515
+ dt = np.datetime64("1970-01-01 05:00:00")
516
+ tzstr = "UTC+05:00"
517
+
518
+ # pre-2.0 this interpreted dt as a UTC time. in 2.0 this is treated
519
+ # as a wall-time, consistent with DatetimeIndex behavior
520
+ ts = Timestamp(dt, tz=tzstr)
521
+
522
+ alt = Timestamp(dt).tz_localize(tzstr)
523
+ assert ts == alt
524
+ assert ts.hour == 5
525
+
526
+ def test_constructor(self):
527
+ base_str = "2014-07-01 09:00"
528
+ base_dt = datetime(2014, 7, 1, 9)
529
+ base_expected = 1_404_205_200_000_000_000
530
+
531
+ # confirm base representation is correct
532
+ assert calendar.timegm(base_dt.timetuple()) * 1_000_000_000 == base_expected
533
+
534
+ tests = [
535
+ (base_str, base_dt, base_expected),
536
+ (
537
+ "2014-07-01 10:00",
538
+ datetime(2014, 7, 1, 10),
539
+ base_expected + 3600 * 1_000_000_000,
540
+ ),
541
+ (
542
+ "2014-07-01 09:00:00.000008000",
543
+ datetime(2014, 7, 1, 9, 0, 0, 8),
544
+ base_expected + 8000,
545
+ ),
546
+ (
547
+ "2014-07-01 09:00:00.000000005",
548
+ Timestamp("2014-07-01 09:00:00.000000005"),
549
+ base_expected + 5,
550
+ ),
551
+ ]
552
+
553
+ timezones = [
554
+ (None, 0),
555
+ ("UTC", 0),
556
+ (pytz.utc, 0),
557
+ ("Asia/Tokyo", 9),
558
+ ("US/Eastern", -4),
559
+ ("dateutil/US/Pacific", -7),
560
+ (pytz.FixedOffset(-180), -3),
561
+ (dateutil.tz.tzoffset(None, 18000), 5),
562
+ ]
563
+
564
+ for date_str, date_obj, expected in tests:
565
+ for result in [Timestamp(date_str), Timestamp(date_obj)]:
566
+ result = result.as_unit("ns") # test originally written before non-nano
567
+ # only with timestring
568
+ assert result.as_unit("ns")._value == expected
569
+
570
+ # re-creation shouldn't affect to internal value
571
+ result = Timestamp(result)
572
+ assert result.as_unit("ns")._value == expected
573
+
574
+ # with timezone
575
+ for tz, offset in timezones:
576
+ for result in [Timestamp(date_str, tz=tz), Timestamp(date_obj, tz=tz)]:
577
+ result = result.as_unit(
578
+ "ns"
579
+ ) # test originally written before non-nano
580
+ expected_tz = expected - offset * 3600 * 1_000_000_000
581
+ assert result.as_unit("ns")._value == expected_tz
582
+
583
+ # should preserve tz
584
+ result = Timestamp(result)
585
+ assert result.as_unit("ns")._value == expected_tz
586
+
587
+ # should convert to UTC
588
+ if tz is not None:
589
+ result = Timestamp(result).tz_convert("UTC")
590
+ else:
591
+ result = Timestamp(result, tz="UTC")
592
+ expected_utc = expected - offset * 3600 * 1_000_000_000
593
+ assert result.as_unit("ns")._value == expected_utc
594
+
595
+ def test_constructor_with_stringoffset(self):
596
+ # GH 7833
597
+ base_str = "2014-07-01 11:00:00+02:00"
598
+ base_dt = datetime(2014, 7, 1, 9)
599
+ base_expected = 1_404_205_200_000_000_000
600
+
601
+ # confirm base representation is correct
602
+ assert calendar.timegm(base_dt.timetuple()) * 1_000_000_000 == base_expected
603
+
604
+ tests = [
605
+ (base_str, base_expected),
606
+ ("2014-07-01 12:00:00+02:00", base_expected + 3600 * 1_000_000_000),
607
+ ("2014-07-01 11:00:00.000008000+02:00", base_expected + 8000),
608
+ ("2014-07-01 11:00:00.000000005+02:00", base_expected + 5),
609
+ ]
610
+
611
+ timezones = [
612
+ (None, 0),
613
+ ("UTC", 0),
614
+ (pytz.utc, 0),
615
+ ("Asia/Tokyo", 9),
616
+ ("US/Eastern", -4),
617
+ ("dateutil/US/Pacific", -7),
618
+ (pytz.FixedOffset(-180), -3),
619
+ (dateutil.tz.tzoffset(None, 18000), 5),
620
+ ]
621
+
622
+ for date_str, expected in tests:
623
+ for result in [Timestamp(date_str)]:
624
+ # only with timestring
625
+ assert result.as_unit("ns")._value == expected
626
+
627
+ # re-creation shouldn't affect to internal value
628
+ result = Timestamp(result)
629
+ assert result.as_unit("ns")._value == expected
630
+
631
+ # with timezone
632
+ for tz, offset in timezones:
633
+ result = Timestamp(date_str, tz=tz)
634
+ expected_tz = expected
635
+ assert result.as_unit("ns")._value == expected_tz
636
+
637
+ # should preserve tz
638
+ result = Timestamp(result)
639
+ assert result.as_unit("ns")._value == expected_tz
640
+
641
+ # should convert to UTC
642
+ result = Timestamp(result).tz_convert("UTC")
643
+ expected_utc = expected
644
+ assert result.as_unit("ns")._value == expected_utc
645
+
646
+ # This should be 2013-11-01 05:00 in UTC
647
+ # converted to Chicago tz
648
+ result = Timestamp("2013-11-01 00:00:00-0500", tz="America/Chicago")
649
+ assert result._value == Timestamp("2013-11-01 05:00")._value
650
+ expected = "Timestamp('2013-11-01 00:00:00-0500', tz='America/Chicago')"
651
+ assert repr(result) == expected
652
+ assert result == eval(repr(result))
653
+
654
+ # This should be 2013-11-01 05:00 in UTC
655
+ # converted to Tokyo tz (+09:00)
656
+ result = Timestamp("2013-11-01 00:00:00-0500", tz="Asia/Tokyo")
657
+ assert result._value == Timestamp("2013-11-01 05:00")._value
658
+ expected = "Timestamp('2013-11-01 14:00:00+0900', tz='Asia/Tokyo')"
659
+ assert repr(result) == expected
660
+ assert result == eval(repr(result))
661
+
662
+ # GH11708
663
+ # This should be 2015-11-18 10:00 in UTC
664
+ # converted to Asia/Katmandu
665
+ result = Timestamp("2015-11-18 15:45:00+05:45", tz="Asia/Katmandu")
666
+ assert result._value == Timestamp("2015-11-18 10:00")._value
667
+ expected = "Timestamp('2015-11-18 15:45:00+0545', tz='Asia/Katmandu')"
668
+ assert repr(result) == expected
669
+ assert result == eval(repr(result))
670
+
671
+ # This should be 2015-11-18 10:00 in UTC
672
+ # converted to Asia/Kolkata
673
+ result = Timestamp("2015-11-18 15:30:00+05:30", tz="Asia/Kolkata")
674
+ assert result._value == Timestamp("2015-11-18 10:00")._value
675
+ expected = "Timestamp('2015-11-18 15:30:00+0530', tz='Asia/Kolkata')"
676
+ assert repr(result) == expected
677
+ assert result == eval(repr(result))
678
+
679
+ def test_constructor_invalid(self):
680
+ msg = "Cannot convert input"
681
+ with pytest.raises(TypeError, match=msg):
682
+ Timestamp(slice(2))
683
+ msg = "Cannot convert Period"
684
+ with pytest.raises(ValueError, match=msg):
685
+ Timestamp(Period("1000-01-01"))
686
+
687
+ def test_constructor_invalid_tz(self):
688
+ # GH#17690
689
+ msg = (
690
+ "Argument 'tzinfo' has incorrect type "
691
+ r"\(expected datetime.tzinfo, got str\)"
692
+ )
693
+ with pytest.raises(TypeError, match=msg):
694
+ Timestamp("2017-10-22", tzinfo="US/Eastern")
695
+
696
+ msg = "at most one of"
697
+ with pytest.raises(ValueError, match=msg):
698
+ Timestamp("2017-10-22", tzinfo=pytz.utc, tz="UTC")
699
+
700
+ msg = "Cannot pass a date attribute keyword argument when passing a date string"
701
+ with pytest.raises(ValueError, match=msg):
702
+ # GH#5168
703
+ # case where user tries to pass tz as an arg, not kwarg, gets
704
+ # interpreted as `year`
705
+ Timestamp("2012-01-01", "US/Pacific")
706
+
707
+ def test_constructor_tz_or_tzinfo(self):
708
+ # GH#17943, GH#17690, GH#5168
709
+ stamps = [
710
+ Timestamp(year=2017, month=10, day=22, tz="UTC"),
711
+ Timestamp(year=2017, month=10, day=22, tzinfo=pytz.utc),
712
+ Timestamp(year=2017, month=10, day=22, tz=pytz.utc),
713
+ Timestamp(datetime(2017, 10, 22), tzinfo=pytz.utc),
714
+ Timestamp(datetime(2017, 10, 22), tz="UTC"),
715
+ Timestamp(datetime(2017, 10, 22), tz=pytz.utc),
716
+ ]
717
+ assert all(ts == stamps[0] for ts in stamps)
718
+
719
+ @pytest.mark.parametrize(
720
+ "result",
721
+ [
722
+ Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), nanosecond=1),
723
+ Timestamp(
724
+ year=2000,
725
+ month=1,
726
+ day=2,
727
+ hour=3,
728
+ minute=4,
729
+ second=5,
730
+ microsecond=6,
731
+ nanosecond=1,
732
+ ),
733
+ Timestamp(
734
+ year=2000,
735
+ month=1,
736
+ day=2,
737
+ hour=3,
738
+ minute=4,
739
+ second=5,
740
+ microsecond=6,
741
+ nanosecond=1,
742
+ tz="UTC",
743
+ ),
744
+ Timestamp(2000, 1, 2, 3, 4, 5, 6, None, nanosecond=1),
745
+ Timestamp(2000, 1, 2, 3, 4, 5, 6, tz=pytz.UTC, nanosecond=1),
746
+ ],
747
+ )
748
+ def test_constructor_nanosecond(self, result):
749
+ # GH 18898
750
+ # As of 2.0 (GH 49416), nanosecond should not be accepted positionally
751
+ expected = Timestamp(datetime(2000, 1, 2, 3, 4, 5, 6), tz=result.tz)
752
+ expected = expected + Timedelta(nanoseconds=1)
753
+ assert result == expected
754
+
755
+ @pytest.mark.parametrize("z", ["Z0", "Z00"])
756
+ def test_constructor_invalid_Z0_isostring(self, z):
757
+ # GH 8910
758
+ msg = f"Unknown datetime string format, unable to parse: 2014-11-02 01:00{z}"
759
+ with pytest.raises(ValueError, match=msg):
760
+ Timestamp(f"2014-11-02 01:00{z}")
761
+
762
+ def test_out_of_bounds_integer_value(self):
763
+ # GH#26651 check that we raise OutOfBoundsDatetime, not OverflowError
764
+ msg = str(Timestamp.max._value * 2)
765
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
766
+ Timestamp(Timestamp.max._value * 2)
767
+ msg = str(Timestamp.min._value * 2)
768
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
769
+ Timestamp(Timestamp.min._value * 2)
770
+
771
+ def test_out_of_bounds_value(self):
772
+ one_us = np.timedelta64(1).astype("timedelta64[us]")
773
+
774
+ # By definition we can't go out of bounds in [ns], so we
775
+ # convert the datetime64s to [us] so we can go out of bounds
776
+ min_ts_us = np.datetime64(Timestamp.min).astype("M8[us]") + one_us
777
+ max_ts_us = np.datetime64(Timestamp.max).astype("M8[us]")
778
+
779
+ # No error for the min/max datetimes
780
+ Timestamp(min_ts_us)
781
+ Timestamp(max_ts_us)
782
+
783
+ # We used to raise on these before supporting non-nano
784
+ us_val = NpyDatetimeUnit.NPY_FR_us.value
785
+ assert Timestamp(min_ts_us - one_us)._creso == us_val
786
+ assert Timestamp(max_ts_us + one_us)._creso == us_val
787
+
788
+ # https://github.com/numpy/numpy/issues/22346 for why
789
+ # we can't use the same construction as above with minute resolution
790
+
791
+ # too_low, too_high are the _just_ outside the range of M8[s]
792
+ too_low = np.datetime64("-292277022657-01-27T08:29", "m")
793
+ too_high = np.datetime64("292277026596-12-04T15:31", "m")
794
+
795
+ msg = "Out of bounds"
796
+ # One us less than the minimum is an error
797
+ with pytest.raises(ValueError, match=msg):
798
+ Timestamp(too_low)
799
+
800
+ # One us more than the maximum is an error
801
+ with pytest.raises(ValueError, match=msg):
802
+ Timestamp(too_high)
803
+
804
+ def test_out_of_bounds_string(self):
805
+ msg = "Cannot cast .* to unit='ns' without overflow"
806
+ with pytest.raises(ValueError, match=msg):
807
+ Timestamp("1676-01-01").as_unit("ns")
808
+ with pytest.raises(ValueError, match=msg):
809
+ Timestamp("2263-01-01").as_unit("ns")
810
+
811
+ ts = Timestamp("2263-01-01")
812
+ assert ts.unit == "s"
813
+
814
+ ts = Timestamp("1676-01-01")
815
+ assert ts.unit == "s"
816
+
817
+ def test_barely_out_of_bounds(self):
818
+ # GH#19529
819
+ # GH#19382 close enough to bounds that dropping nanos would result
820
+ # in an in-bounds datetime
821
+ msg = "Out of bounds nanosecond timestamp: 2262-04-11 23:47:16"
822
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
823
+ Timestamp("2262-04-11 23:47:16.854775808")
824
+
825
+ @pytest.mark.skip_ubsan
826
+ def test_bounds_with_different_units(self):
827
+ out_of_bounds_dates = ("1677-09-21", "2262-04-12")
828
+
829
+ time_units = ("D", "h", "m", "s", "ms", "us")
830
+
831
+ for date_string in out_of_bounds_dates:
832
+ for unit in time_units:
833
+ dt64 = np.datetime64(date_string, unit)
834
+ ts = Timestamp(dt64)
835
+ if unit in ["s", "ms", "us"]:
836
+ # We can preserve the input unit
837
+ assert ts._value == dt64.view("i8")
838
+ else:
839
+ # we chose the closest unit that we _do_ support
840
+ assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value
841
+
842
+ # With more extreme cases, we can't even fit inside second resolution
843
+ info = np.iinfo(np.int64)
844
+ msg = "Out of bounds second timestamp:"
845
+ for value in [info.min + 1, info.max]:
846
+ for unit in ["D", "h", "m"]:
847
+ dt64 = np.datetime64(value, unit)
848
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
849
+ Timestamp(dt64)
850
+
851
+ in_bounds_dates = ("1677-09-23", "2262-04-11")
852
+
853
+ for date_string in in_bounds_dates:
854
+ for unit in time_units:
855
+ dt64 = np.datetime64(date_string, unit)
856
+ Timestamp(dt64)
857
+
858
+ @pytest.mark.parametrize("arg", ["001-01-01", "0001-01-01"])
859
+ def test_out_of_bounds_string_consistency(self, arg):
860
+ # GH 15829
861
+ msg = "Cannot cast 0001-01-01 00:00:00 to unit='ns' without overflow"
862
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
863
+ Timestamp(arg).as_unit("ns")
864
+
865
+ ts = Timestamp(arg)
866
+ assert ts.unit == "s"
867
+ assert ts.year == ts.month == ts.day == 1
868
+
869
+ def test_min_valid(self):
870
+ # Ensure that Timestamp.min is a valid Timestamp
871
+ Timestamp(Timestamp.min)
872
+
873
+ def test_max_valid(self):
874
+ # Ensure that Timestamp.max is a valid Timestamp
875
+ Timestamp(Timestamp.max)
876
+
877
+ @pytest.mark.parametrize("offset", ["+0300", "+0200"])
878
+ def test_construct_timestamp_near_dst(self, offset):
879
+ # GH 20854
880
+ expected = Timestamp(f"2016-10-30 03:00:00{offset}", tz="Europe/Helsinki")
881
+ result = Timestamp(expected).tz_convert("Europe/Helsinki")
882
+ assert result == expected
883
+
884
+ @pytest.mark.parametrize(
885
+ "arg", ["2013/01/01 00:00:00+09:00", "2013-01-01 00:00:00+09:00"]
886
+ )
887
+ def test_construct_with_different_string_format(self, arg):
888
+ # GH 12064
889
+ result = Timestamp(arg)
890
+ expected = Timestamp(datetime(2013, 1, 1), tz=pytz.FixedOffset(540))
891
+ assert result == expected
892
+
893
+ @pytest.mark.parametrize("box", [datetime, Timestamp])
894
+ def test_raise_tz_and_tzinfo_in_datetime_input(self, box):
895
+ # GH 23579
896
+ kwargs = {"year": 2018, "month": 1, "day": 1, "tzinfo": pytz.utc}
897
+ msg = "Cannot pass a datetime or Timestamp"
898
+ with pytest.raises(ValueError, match=msg):
899
+ Timestamp(box(**kwargs), tz="US/Pacific")
900
+ msg = "Cannot pass a datetime or Timestamp"
901
+ with pytest.raises(ValueError, match=msg):
902
+ Timestamp(box(**kwargs), tzinfo=pytz.timezone("US/Pacific"))
903
+
904
+ def test_dont_convert_dateutil_utc_to_pytz_utc(self):
905
+ result = Timestamp(datetime(2018, 1, 1), tz=tzutc())
906
+ expected = Timestamp(datetime(2018, 1, 1)).tz_localize(tzutc())
907
+ assert result == expected
908
+
909
+ def test_constructor_subclassed_datetime(self):
910
+ # GH 25851
911
+ # ensure that subclassed datetime works for
912
+ # Timestamp creation
913
+ class SubDatetime(datetime):
914
+ pass
915
+
916
+ data = SubDatetime(2000, 1, 1)
917
+ result = Timestamp(data)
918
+ expected = Timestamp(2000, 1, 1)
919
+ assert result == expected
920
+
921
+ def test_timestamp_constructor_tz_utc(self):
922
+ utc_stamp = Timestamp("3/11/2012 05:00", tz="utc")
923
+ assert utc_stamp.tzinfo is timezone.utc
924
+ assert utc_stamp.hour == 5
925
+
926
+ utc_stamp = Timestamp("3/11/2012 05:00").tz_localize("utc")
927
+ assert utc_stamp.hour == 5
928
+
929
+ def test_timestamp_to_datetime_tzoffset(self):
930
+ tzinfo = tzoffset(None, 7200)
931
+ expected = Timestamp("3/11/2012 04:00", tz=tzinfo)
932
+ result = Timestamp(expected.to_pydatetime())
933
+ assert expected == result
934
+
935
+ def test_timestamp_constructor_near_dst_boundary(self):
936
+ # GH#11481 & GH#15777
937
+ # Naive string timestamps were being localized incorrectly
938
+ # with tz_convert_from_utc_single instead of tz_localize_to_utc
939
+
940
+ for tz in ["Europe/Brussels", "Europe/Prague"]:
941
+ result = Timestamp("2015-10-25 01:00", tz=tz)
942
+ expected = Timestamp("2015-10-25 01:00").tz_localize(tz)
943
+ assert result == expected
944
+
945
+ msg = "Cannot infer dst time from 2015-10-25 02:00:00"
946
+ with pytest.raises(pytz.AmbiguousTimeError, match=msg):
947
+ Timestamp("2015-10-25 02:00", tz=tz)
948
+
949
+ result = Timestamp("2017-03-26 01:00", tz="Europe/Paris")
950
+ expected = Timestamp("2017-03-26 01:00").tz_localize("Europe/Paris")
951
+ assert result == expected
952
+
953
+ msg = "2017-03-26 02:00"
954
+ with pytest.raises(pytz.NonExistentTimeError, match=msg):
955
+ Timestamp("2017-03-26 02:00", tz="Europe/Paris")
956
+
957
+ # GH#11708
958
+ naive = Timestamp("2015-11-18 10:00:00")
959
+ result = naive.tz_localize("UTC").tz_convert("Asia/Kolkata")
960
+ expected = Timestamp("2015-11-18 15:30:00+0530", tz="Asia/Kolkata")
961
+ assert result == expected
962
+
963
+ # GH#15823
964
+ result = Timestamp("2017-03-26 00:00", tz="Europe/Paris")
965
+ expected = Timestamp("2017-03-26 00:00:00+0100", tz="Europe/Paris")
966
+ assert result == expected
967
+
968
+ result = Timestamp("2017-03-26 01:00", tz="Europe/Paris")
969
+ expected = Timestamp("2017-03-26 01:00:00+0100", tz="Europe/Paris")
970
+ assert result == expected
971
+
972
+ msg = "2017-03-26 02:00"
973
+ with pytest.raises(pytz.NonExistentTimeError, match=msg):
974
+ Timestamp("2017-03-26 02:00", tz="Europe/Paris")
975
+
976
+ result = Timestamp("2017-03-26 02:00:00+0100", tz="Europe/Paris")
977
+ naive = Timestamp(result.as_unit("ns")._value)
978
+ expected = naive.tz_localize("UTC").tz_convert("Europe/Paris")
979
+ assert result == expected
980
+
981
+ result = Timestamp("2017-03-26 03:00", tz="Europe/Paris")
982
+ expected = Timestamp("2017-03-26 03:00:00+0200", tz="Europe/Paris")
983
+ assert result == expected
984
+
985
+ @pytest.mark.parametrize(
986
+ "tz",
987
+ [
988
+ pytz.timezone("US/Eastern"),
989
+ gettz("US/Eastern"),
990
+ "US/Eastern",
991
+ "dateutil/US/Eastern",
992
+ ],
993
+ )
994
+ def test_timestamp_constructed_by_date_and_tz(self, tz):
995
+ # GH#2993, Timestamp cannot be constructed by datetime.date
996
+ # and tz correctly
997
+
998
+ result = Timestamp(date(2012, 3, 11), tz=tz)
999
+
1000
+ expected = Timestamp("3/11/2012", tz=tz)
1001
+ assert result.hour == expected.hour
1002
+ assert result == expected
1003
+
1004
+
1005
+ def test_constructor_ambiguous_dst():
1006
+ # GH 24329
1007
+ # Make sure that calling Timestamp constructor
1008
+ # on Timestamp created from ambiguous time
1009
+ # doesn't change Timestamp.value
1010
+ ts = Timestamp(1382835600000000000, tz="dateutil/Europe/London")
1011
+ expected = ts._value
1012
+ result = Timestamp(ts)._value
1013
+ assert result == expected
1014
+
1015
+
1016
+ @pytest.mark.parametrize("epoch", [1552211999999999872, 1552211999999999999])
1017
+ def test_constructor_before_dst_switch(epoch):
1018
+ # GH 31043
1019
+ # Make sure that calling Timestamp constructor
1020
+ # on time just before DST switch doesn't lead to
1021
+ # nonexistent time or value change
1022
+ ts = Timestamp(epoch, tz="dateutil/America/Los_Angeles")
1023
+ result = ts.tz.dst(ts)
1024
+ expected = timedelta(seconds=0)
1025
+ assert Timestamp(ts)._value == epoch
1026
+ assert result == expected
1027
+
1028
+
1029
+ def test_timestamp_constructor_identity():
1030
+ # Test for #30543
1031
+ expected = Timestamp("2017-01-01T12")
1032
+ result = Timestamp(expected)
1033
+ assert result is expected
1034
+
1035
+
1036
+ @pytest.mark.parametrize("nano", [-1, 1000])
1037
+ def test_timestamp_nano_range(nano):
1038
+ # GH 48255
1039
+ with pytest.raises(ValueError, match="nanosecond must be in 0..999"):
1040
+ Timestamp(year=2022, month=1, day=1, nanosecond=nano)
1041
+
1042
+
1043
+ def test_non_nano_value():
1044
+ # https://github.com/pandas-dev/pandas/issues/49076
1045
+ result = Timestamp("1800-01-01", unit="s").value
1046
+ # `.value` shows nanoseconds, even though unit is 's'
1047
+ assert result == -5364662400000000000
1048
+
1049
+ # out-of-nanoseconds-bounds `.value` raises informative message
1050
+ msg = (
1051
+ r"Cannot convert Timestamp to nanoseconds without overflow. "
1052
+ r"Use `.asm8.view\('i8'\)` to cast represent Timestamp in its "
1053
+ r"own unit \(here, s\).$"
1054
+ )
1055
+ ts = Timestamp("0300-01-01")
1056
+ with pytest.raises(OverflowError, match=msg):
1057
+ ts.value
1058
+ # check that the suggested workaround actually works
1059
+ result = ts.asm8.view("i8")
1060
+ assert result == -52700112000
1061
+
1062
+
1063
+ @pytest.mark.parametrize("na_value", [None, np.nan, np.datetime64("NaT"), NaT, NA])
1064
+ def test_timestamp_constructor_na_value(na_value):
1065
+ # GH45481
1066
+ result = Timestamp(na_value)
1067
+ expected = NaT
1068
+ assert result is expected
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_formats.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import pprint
3
+
4
+ import dateutil.tz
5
+ import pytest
6
+ import pytz # a test below uses pytz but only inside a `eval` call
7
+
8
+ from pandas import Timestamp
9
+
10
+ ts_no_ns = Timestamp(
11
+ year=2019,
12
+ month=5,
13
+ day=18,
14
+ hour=15,
15
+ minute=17,
16
+ second=8,
17
+ microsecond=132263,
18
+ )
19
+ ts_no_ns_year1 = Timestamp(
20
+ year=1,
21
+ month=5,
22
+ day=18,
23
+ hour=15,
24
+ minute=17,
25
+ second=8,
26
+ microsecond=132263,
27
+ )
28
+ ts_ns = Timestamp(
29
+ year=2019,
30
+ month=5,
31
+ day=18,
32
+ hour=15,
33
+ minute=17,
34
+ second=8,
35
+ microsecond=132263,
36
+ nanosecond=123,
37
+ )
38
+ ts_ns_tz = Timestamp(
39
+ year=2019,
40
+ month=5,
41
+ day=18,
42
+ hour=15,
43
+ minute=17,
44
+ second=8,
45
+ microsecond=132263,
46
+ nanosecond=123,
47
+ tz="UTC",
48
+ )
49
+ ts_no_us = Timestamp(
50
+ year=2019,
51
+ month=5,
52
+ day=18,
53
+ hour=15,
54
+ minute=17,
55
+ second=8,
56
+ microsecond=0,
57
+ nanosecond=123,
58
+ )
59
+
60
+
61
+ @pytest.mark.parametrize(
62
+ "ts, timespec, expected_iso",
63
+ [
64
+ (ts_no_ns, "auto", "2019-05-18T15:17:08.132263"),
65
+ (ts_no_ns, "seconds", "2019-05-18T15:17:08"),
66
+ (ts_no_ns, "nanoseconds", "2019-05-18T15:17:08.132263000"),
67
+ (ts_no_ns_year1, "seconds", "0001-05-18T15:17:08"),
68
+ (ts_no_ns_year1, "nanoseconds", "0001-05-18T15:17:08.132263000"),
69
+ (ts_ns, "auto", "2019-05-18T15:17:08.132263123"),
70
+ (ts_ns, "hours", "2019-05-18T15"),
71
+ (ts_ns, "minutes", "2019-05-18T15:17"),
72
+ (ts_ns, "seconds", "2019-05-18T15:17:08"),
73
+ (ts_ns, "milliseconds", "2019-05-18T15:17:08.132"),
74
+ (ts_ns, "microseconds", "2019-05-18T15:17:08.132263"),
75
+ (ts_ns, "nanoseconds", "2019-05-18T15:17:08.132263123"),
76
+ (ts_ns_tz, "auto", "2019-05-18T15:17:08.132263123+00:00"),
77
+ (ts_ns_tz, "hours", "2019-05-18T15+00:00"),
78
+ (ts_ns_tz, "minutes", "2019-05-18T15:17+00:00"),
79
+ (ts_ns_tz, "seconds", "2019-05-18T15:17:08+00:00"),
80
+ (ts_ns_tz, "milliseconds", "2019-05-18T15:17:08.132+00:00"),
81
+ (ts_ns_tz, "microseconds", "2019-05-18T15:17:08.132263+00:00"),
82
+ (ts_ns_tz, "nanoseconds", "2019-05-18T15:17:08.132263123+00:00"),
83
+ (ts_no_us, "auto", "2019-05-18T15:17:08.000000123"),
84
+ ],
85
+ )
86
+ def test_isoformat(ts, timespec, expected_iso):
87
+ assert ts.isoformat(timespec=timespec) == expected_iso
88
+
89
+
90
+ class TestTimestampRendering:
91
+ timezones = ["UTC", "Asia/Tokyo", "US/Eastern", "dateutil/America/Los_Angeles"]
92
+
93
+ @pytest.mark.parametrize("tz", timezones)
94
+ @pytest.mark.parametrize("freq", ["D", "M", "S", "N"])
95
+ @pytest.mark.parametrize(
96
+ "date", ["2014-03-07", "2014-01-01 09:00", "2014-01-01 00:00:00.000000001"]
97
+ )
98
+ def test_repr(self, date, freq, tz):
99
+ # avoid to match with timezone name
100
+ freq_repr = f"'{freq}'"
101
+ if tz.startswith("dateutil"):
102
+ tz_repr = tz.replace("dateutil", "")
103
+ else:
104
+ tz_repr = tz
105
+
106
+ date_only = Timestamp(date)
107
+ assert date in repr(date_only)
108
+ assert tz_repr not in repr(date_only)
109
+ assert freq_repr not in repr(date_only)
110
+ assert date_only == eval(repr(date_only))
111
+
112
+ date_tz = Timestamp(date, tz=tz)
113
+ assert date in repr(date_tz)
114
+ assert tz_repr in repr(date_tz)
115
+ assert freq_repr not in repr(date_tz)
116
+ assert date_tz == eval(repr(date_tz))
117
+
118
+ def test_repr_utcoffset(self):
119
+ # This can cause the tz field to be populated, but it's redundant to
120
+ # include this information in the date-string.
121
+ date_with_utc_offset = Timestamp("2014-03-13 00:00:00-0400", tz=None)
122
+ assert "2014-03-13 00:00:00-0400" in repr(date_with_utc_offset)
123
+ assert "tzoffset" not in repr(date_with_utc_offset)
124
+ assert "UTC-04:00" in repr(date_with_utc_offset)
125
+ expr = repr(date_with_utc_offset)
126
+ assert date_with_utc_offset == eval(expr)
127
+
128
+ def test_timestamp_repr_pre1900(self):
129
+ # pre-1900
130
+ stamp = Timestamp("1850-01-01", tz="US/Eastern")
131
+ repr(stamp)
132
+
133
+ iso8601 = "1850-01-01 01:23:45.012345"
134
+ stamp = Timestamp(iso8601, tz="US/Eastern")
135
+ result = repr(stamp)
136
+ assert iso8601 in result
137
+
138
+ def test_pprint(self):
139
+ # GH#12622
140
+ nested_obj = {"foo": 1, "bar": [{"w": {"a": Timestamp("2011-01-01")}}] * 10}
141
+ result = pprint.pformat(nested_obj, width=50)
142
+ expected = r"""{'bar': [{'w': {'a': Timestamp('2011-01-01 00:00:00')}},
143
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
144
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
145
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
146
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
147
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
148
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
149
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
150
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}},
151
+ {'w': {'a': Timestamp('2011-01-01 00:00:00')}}],
152
+ 'foo': 1}"""
153
+ assert result == expected
154
+
155
+ def test_to_timestamp_repr_is_code(self):
156
+ zs = [
157
+ Timestamp("99-04-17 00:00:00", tz="UTC"),
158
+ Timestamp("2001-04-17 00:00:00", tz="UTC"),
159
+ Timestamp("2001-04-17 00:00:00", tz="America/Los_Angeles"),
160
+ Timestamp("2001-04-17 00:00:00", tz=None),
161
+ ]
162
+ for z in zs:
163
+ assert eval(repr(z)) == z
164
+
165
+ def test_repr_matches_pydatetime_no_tz(self):
166
+ dt_date = datetime(2013, 1, 2)
167
+ assert str(dt_date) == str(Timestamp(dt_date))
168
+
169
+ dt_datetime = datetime(2013, 1, 2, 12, 1, 3)
170
+ assert str(dt_datetime) == str(Timestamp(dt_datetime))
171
+
172
+ dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45)
173
+ assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
174
+
175
+ ts_nanos_only = Timestamp(200)
176
+ assert str(ts_nanos_only) == "1970-01-01 00:00:00.000000200"
177
+
178
+ ts_nanos_micros = Timestamp(1200)
179
+ assert str(ts_nanos_micros) == "1970-01-01 00:00:00.000001200"
180
+
181
+ def test_repr_matches_pydatetime_tz_pytz(self):
182
+ dt_date = datetime(2013, 1, 2, tzinfo=pytz.utc)
183
+ assert str(dt_date) == str(Timestamp(dt_date))
184
+
185
+ dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=pytz.utc)
186
+ assert str(dt_datetime) == str(Timestamp(dt_datetime))
187
+
188
+ dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=pytz.utc)
189
+ assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
190
+
191
+ def test_repr_matches_pydatetime_tz_dateutil(self):
192
+ utc = dateutil.tz.tzutc()
193
+
194
+ dt_date = datetime(2013, 1, 2, tzinfo=utc)
195
+ assert str(dt_date) == str(Timestamp(dt_date))
196
+
197
+ dt_datetime = datetime(2013, 1, 2, 12, 1, 3, tzinfo=utc)
198
+ assert str(dt_datetime) == str(Timestamp(dt_datetime))
199
+
200
+ dt_datetime_us = datetime(2013, 1, 2, 12, 1, 3, 45, tzinfo=utc)
201
+ assert str(dt_datetime_us) == str(Timestamp(dt_datetime_us))
env-llmeval/lib/python3.10/site-packages/pandas/tests/scalar/timestamp/test_timestamp.py ADDED
@@ -0,0 +1,928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ test the scalar Timestamp """
2
+
3
+ import calendar
4
+ from datetime import (
5
+ datetime,
6
+ timedelta,
7
+ timezone,
8
+ )
9
+ import locale
10
+ import time
11
+ import unicodedata
12
+
13
+ from dateutil.tz import (
14
+ tzlocal,
15
+ tzutc,
16
+ )
17
+ from hypothesis import (
18
+ given,
19
+ strategies as st,
20
+ )
21
+ import numpy as np
22
+ import pytest
23
+ import pytz
24
+ from pytz import utc
25
+
26
+ from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
27
+ from pandas._libs.tslibs.timezones import (
28
+ dateutil_gettz as gettz,
29
+ get_timezone,
30
+ maybe_get_tz,
31
+ tz_compare,
32
+ )
33
+ from pandas.compat import IS64
34
+
35
+ from pandas import (
36
+ NaT,
37
+ Timedelta,
38
+ Timestamp,
39
+ )
40
+ import pandas._testing as tm
41
+
42
+ from pandas.tseries import offsets
43
+ from pandas.tseries.frequencies import to_offset
44
+
45
+
46
+ class TestTimestampProperties:
47
+ def test_properties_business(self):
48
+ freq = to_offset("B")
49
+
50
+ ts = Timestamp("2017-10-01")
51
+ assert ts.dayofweek == 6
52
+ assert ts.day_of_week == 6
53
+ assert ts.is_month_start # not a weekday
54
+ assert not freq.is_month_start(ts)
55
+ assert freq.is_month_start(ts + Timedelta(days=1))
56
+ assert not freq.is_quarter_start(ts)
57
+ assert freq.is_quarter_start(ts + Timedelta(days=1))
58
+
59
+ ts = Timestamp("2017-09-30")
60
+ assert ts.dayofweek == 5
61
+ assert ts.day_of_week == 5
62
+ assert ts.is_month_end
63
+ assert not freq.is_month_end(ts)
64
+ assert freq.is_month_end(ts - Timedelta(days=1))
65
+ assert ts.is_quarter_end
66
+ assert not freq.is_quarter_end(ts)
67
+ assert freq.is_quarter_end(ts - Timedelta(days=1))
68
+
69
+ @pytest.mark.parametrize(
70
+ "attr, expected",
71
+ [
72
+ ["year", 2014],
73
+ ["month", 12],
74
+ ["day", 31],
75
+ ["hour", 23],
76
+ ["minute", 59],
77
+ ["second", 0],
78
+ ["microsecond", 0],
79
+ ["nanosecond", 0],
80
+ ["dayofweek", 2],
81
+ ["day_of_week", 2],
82
+ ["quarter", 4],
83
+ ["dayofyear", 365],
84
+ ["day_of_year", 365],
85
+ ["week", 1],
86
+ ["daysinmonth", 31],
87
+ ],
88
+ )
89
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
90
+ def test_fields(self, attr, expected, tz):
91
+ # GH 10050
92
+ # GH 13303
93
+ ts = Timestamp("2014-12-31 23:59:00", tz=tz)
94
+ result = getattr(ts, attr)
95
+ # that we are int like
96
+ assert isinstance(result, int)
97
+ assert result == expected
98
+
99
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
100
+ def test_millisecond_raises(self, tz):
101
+ ts = Timestamp("2014-12-31 23:59:00", tz=tz)
102
+ msg = "'Timestamp' object has no attribute 'millisecond'"
103
+ with pytest.raises(AttributeError, match=msg):
104
+ ts.millisecond
105
+
106
+ @pytest.mark.parametrize(
107
+ "start", ["is_month_start", "is_quarter_start", "is_year_start"]
108
+ )
109
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
110
+ def test_is_start(self, start, tz):
111
+ ts = Timestamp("2014-01-01 00:00:00", tz=tz)
112
+ assert getattr(ts, start)
113
+
114
+ @pytest.mark.parametrize("end", ["is_month_end", "is_year_end", "is_quarter_end"])
115
+ @pytest.mark.parametrize("tz", [None, "US/Eastern"])
116
+ def test_is_end(self, end, tz):
117
+ ts = Timestamp("2014-12-31 23:59:59", tz=tz)
118
+ assert getattr(ts, end)
119
+
120
+ # GH 12806
121
+ @pytest.mark.parametrize(
122
+ "data",
123
+ [Timestamp("2017-08-28 23:00:00"), Timestamp("2017-08-28 23:00:00", tz="EST")],
124
+ )
125
+ # error: Unsupported operand types for + ("List[None]" and "List[str]")
126
+ @pytest.mark.parametrize(
127
+ "time_locale", [None] + tm.get_locales() # type: ignore[operator]
128
+ )
129
+ def test_names(self, data, time_locale):
130
+ # GH 17354
131
+ # Test .day_name(), .month_name
132
+ if time_locale is None:
133
+ expected_day = "Monday"
134
+ expected_month = "August"
135
+ else:
136
+ with tm.set_locale(time_locale, locale.LC_TIME):
137
+ expected_day = calendar.day_name[0].capitalize()
138
+ expected_month = calendar.month_name[8].capitalize()
139
+
140
+ result_day = data.day_name(time_locale)
141
+ result_month = data.month_name(time_locale)
142
+
143
+ # Work around https://github.com/pandas-dev/pandas/issues/22342
144
+ # different normalizations
145
+ expected_day = unicodedata.normalize("NFD", expected_day)
146
+ expected_month = unicodedata.normalize("NFD", expected_month)
147
+
148
+ result_day = unicodedata.normalize("NFD", result_day)
149
+ result_month = unicodedata.normalize("NFD", result_month)
150
+
151
+ assert result_day == expected_day
152
+ assert result_month == expected_month
153
+
154
+ # Test NaT
155
+ nan_ts = Timestamp(NaT)
156
+ assert np.isnan(nan_ts.day_name(time_locale))
157
+ assert np.isnan(nan_ts.month_name(time_locale))
158
+
159
+ def test_is_leap_year(self, tz_naive_fixture):
160
+ tz = tz_naive_fixture
161
+ if not IS64 and tz == tzlocal():
162
+ # https://github.com/dateutil/dateutil/issues/197
163
+ pytest.skip(
164
+ "tzlocal() on a 32 bit platform causes internal overflow errors"
165
+ )
166
+ # GH 13727
167
+ dt = Timestamp("2000-01-01 00:00:00", tz=tz)
168
+ assert dt.is_leap_year
169
+ assert isinstance(dt.is_leap_year, bool)
170
+
171
+ dt = Timestamp("1999-01-01 00:00:00", tz=tz)
172
+ assert not dt.is_leap_year
173
+
174
+ dt = Timestamp("2004-01-01 00:00:00", tz=tz)
175
+ assert dt.is_leap_year
176
+
177
+ dt = Timestamp("2100-01-01 00:00:00", tz=tz)
178
+ assert not dt.is_leap_year
179
+
180
+ def test_woy_boundary(self):
181
+ # make sure weeks at year boundaries are correct
182
+ d = datetime(2013, 12, 31)
183
+ result = Timestamp(d).week
184
+ expected = 1 # ISO standard
185
+ assert result == expected
186
+
187
+ d = datetime(2008, 12, 28)
188
+ result = Timestamp(d).week
189
+ expected = 52 # ISO standard
190
+ assert result == expected
191
+
192
+ d = datetime(2009, 12, 31)
193
+ result = Timestamp(d).week
194
+ expected = 53 # ISO standard
195
+ assert result == expected
196
+
197
+ d = datetime(2010, 1, 1)
198
+ result = Timestamp(d).week
199
+ expected = 53 # ISO standard
200
+ assert result == expected
201
+
202
+ d = datetime(2010, 1, 3)
203
+ result = Timestamp(d).week
204
+ expected = 53 # ISO standard
205
+ assert result == expected
206
+
207
+ result = np.array(
208
+ [
209
+ Timestamp(datetime(*args)).week
210
+ for args in [(2000, 1, 1), (2000, 1, 2), (2005, 1, 1), (2005, 1, 2)]
211
+ ]
212
+ )
213
+ assert (result == [52, 52, 53, 53]).all()
214
+
215
+ def test_resolution(self):
216
+ # GH#21336, GH#21365
217
+ dt = Timestamp("2100-01-01 00:00:00.000000000")
218
+ assert dt.resolution == Timedelta(nanoseconds=1)
219
+
220
+ # Check that the attribute is available on the class, mirroring
221
+ # the stdlib datetime behavior
222
+ assert Timestamp.resolution == Timedelta(nanoseconds=1)
223
+
224
+ assert dt.as_unit("us").resolution == Timedelta(microseconds=1)
225
+ assert dt.as_unit("ms").resolution == Timedelta(milliseconds=1)
226
+ assert dt.as_unit("s").resolution == Timedelta(seconds=1)
227
+
228
+ @pytest.mark.parametrize(
229
+ "date_string, expected",
230
+ [
231
+ ("0000-2-29", 1),
232
+ ("0000-3-1", 2),
233
+ ("1582-10-14", 3),
234
+ ("-0040-1-1", 4),
235
+ ("2023-06-18", 6),
236
+ ],
237
+ )
238
+ def test_dow_historic(self, date_string, expected):
239
+ # GH 53738
240
+ ts = Timestamp(date_string)
241
+ dow = ts.weekday()
242
+ assert dow == expected
243
+
244
+ @given(
245
+ ts=st.datetimes(),
246
+ sign=st.sampled_from(["-", ""]),
247
+ )
248
+ def test_dow_parametric(self, ts, sign):
249
+ # GH 53738
250
+ ts = (
251
+ f"{sign}{str(ts.year).zfill(4)}"
252
+ f"-{str(ts.month).zfill(2)}"
253
+ f"-{str(ts.day).zfill(2)}"
254
+ )
255
+ result = Timestamp(ts).weekday()
256
+ expected = (
257
+ (np.datetime64(ts) - np.datetime64("1970-01-01")).astype("int64") - 4
258
+ ) % 7
259
+ assert result == expected
260
+
261
+
262
+ class TestTimestamp:
263
+ @pytest.mark.parametrize("tz", [None, pytz.timezone("US/Pacific")])
264
+ def test_disallow_setting_tz(self, tz):
265
+ # GH#3746
266
+ ts = Timestamp("2010")
267
+ msg = "Cannot directly set timezone"
268
+ with pytest.raises(AttributeError, match=msg):
269
+ ts.tz = tz
270
+
271
+ def test_default_to_stdlib_utc(self):
272
+ assert Timestamp.utcnow().tz is timezone.utc
273
+ assert Timestamp.now("UTC").tz is timezone.utc
274
+ assert Timestamp("2016-01-01", tz="UTC").tz is timezone.utc
275
+
276
+ def test_tz(self):
277
+ tstr = "2014-02-01 09:00"
278
+ ts = Timestamp(tstr)
279
+ local = ts.tz_localize("Asia/Tokyo")
280
+ assert local.hour == 9
281
+ assert local == Timestamp(tstr, tz="Asia/Tokyo")
282
+ conv = local.tz_convert("US/Eastern")
283
+ assert conv == Timestamp("2014-01-31 19:00", tz="US/Eastern")
284
+ assert conv.hour == 19
285
+
286
+ # preserves nanosecond
287
+ ts = Timestamp(tstr) + offsets.Nano(5)
288
+ local = ts.tz_localize("Asia/Tokyo")
289
+ assert local.hour == 9
290
+ assert local.nanosecond == 5
291
+ conv = local.tz_convert("US/Eastern")
292
+ assert conv.nanosecond == 5
293
+ assert conv.hour == 19
294
+
295
+ def test_utc_z_designator(self):
296
+ assert get_timezone(Timestamp("2014-11-02 01:00Z").tzinfo) is timezone.utc
297
+
298
+ def test_asm8(self):
299
+ ns = [Timestamp.min._value, Timestamp.max._value, 1000]
300
+
301
+ for n in ns:
302
+ assert (
303
+ Timestamp(n).asm8.view("i8") == np.datetime64(n, "ns").view("i8") == n
304
+ )
305
+
306
+ assert Timestamp("nat").asm8.view("i8") == np.datetime64("nat", "ns").view("i8")
307
+
308
+ def test_class_ops(self):
309
+ def compare(x, y):
310
+ assert int((Timestamp(x)._value - Timestamp(y)._value) / 1e9) == 0
311
+
312
+ compare(Timestamp.now(), datetime.now())
313
+ compare(Timestamp.now("UTC"), datetime.now(pytz.timezone("UTC")))
314
+ compare(Timestamp.now("UTC"), datetime.now(tzutc()))
315
+ compare(Timestamp.utcnow(), datetime.now(timezone.utc))
316
+ compare(Timestamp.today(), datetime.today())
317
+ current_time = calendar.timegm(datetime.now().utctimetuple())
318
+
319
+ ts_utc = Timestamp.utcfromtimestamp(current_time)
320
+ assert ts_utc.timestamp() == current_time
321
+ compare(
322
+ Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)
323
+ )
324
+ compare(
325
+ # Support tz kwarg in Timestamp.fromtimestamp
326
+ Timestamp.fromtimestamp(current_time, "UTC"),
327
+ datetime.fromtimestamp(current_time, utc),
328
+ )
329
+ compare(
330
+ # Support tz kwarg in Timestamp.fromtimestamp
331
+ Timestamp.fromtimestamp(current_time, tz="UTC"),
332
+ datetime.fromtimestamp(current_time, utc),
333
+ )
334
+
335
+ date_component = datetime.now(timezone.utc)
336
+ time_component = (date_component + timedelta(minutes=10)).time()
337
+ compare(
338
+ Timestamp.combine(date_component, time_component),
339
+ datetime.combine(date_component, time_component),
340
+ )
341
+
342
+ def test_basics_nanos(self):
343
+ val = np.int64(946_684_800_000_000_000).view("M8[ns]")
344
+ stamp = Timestamp(val.view("i8") + 500)
345
+ assert stamp.year == 2000
346
+ assert stamp.month == 1
347
+ assert stamp.microsecond == 0
348
+ assert stamp.nanosecond == 500
349
+
350
+ # GH 14415
351
+ val = np.iinfo(np.int64).min + 80_000_000_000_000
352
+ stamp = Timestamp(val)
353
+ assert stamp.year == 1677
354
+ assert stamp.month == 9
355
+ assert stamp.day == 21
356
+ assert stamp.microsecond == 145224
357
+ assert stamp.nanosecond == 192
358
+
359
+ def test_roundtrip(self):
360
+ # test value to string and back conversions
361
+ # further test accessors
362
+ base = Timestamp("20140101 00:00:00").as_unit("ns")
363
+
364
+ result = Timestamp(base._value + Timedelta("5ms")._value)
365
+ assert result == Timestamp(f"{base}.005000")
366
+ assert result.microsecond == 5000
367
+
368
+ result = Timestamp(base._value + Timedelta("5us")._value)
369
+ assert result == Timestamp(f"{base}.000005")
370
+ assert result.microsecond == 5
371
+
372
+ result = Timestamp(base._value + Timedelta("5ns")._value)
373
+ assert result == Timestamp(f"{base}.000000005")
374
+ assert result.nanosecond == 5
375
+ assert result.microsecond == 0
376
+
377
+ result = Timestamp(base._value + Timedelta("6ms 5us")._value)
378
+ assert result == Timestamp(f"{base}.006005")
379
+ assert result.microsecond == 5 + 6 * 1000
380
+
381
+ result = Timestamp(base._value + Timedelta("200ms 5us")._value)
382
+ assert result == Timestamp(f"{base}.200005")
383
+ assert result.microsecond == 5 + 200 * 1000
384
+
385
+ def test_hash_equivalent(self):
386
+ d = {datetime(2011, 1, 1): 5}
387
+ stamp = Timestamp(datetime(2011, 1, 1))
388
+ assert d[stamp] == 5
389
+
390
+ @pytest.mark.parametrize(
391
+ "timezone, year, month, day, hour",
392
+ [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]],
393
+ )
394
+ def test_hash_timestamp_with_fold(self, timezone, year, month, day, hour):
395
+ # see gh-33931
396
+ test_timezone = gettz(timezone)
397
+ transition_1 = Timestamp(
398
+ year=year,
399
+ month=month,
400
+ day=day,
401
+ hour=hour,
402
+ minute=0,
403
+ fold=0,
404
+ tzinfo=test_timezone,
405
+ )
406
+ transition_2 = Timestamp(
407
+ year=year,
408
+ month=month,
409
+ day=day,
410
+ hour=hour,
411
+ minute=0,
412
+ fold=1,
413
+ tzinfo=test_timezone,
414
+ )
415
+ assert hash(transition_1) == hash(transition_2)
416
+
417
+
418
+ class TestTimestampNsOperations:
419
+ def test_nanosecond_string_parsing(self):
420
+ ts = Timestamp("2013-05-01 07:15:45.123456789")
421
+ # GH 7878
422
+ expected_repr = "2013-05-01 07:15:45.123456789"
423
+ expected_value = 1_367_392_545_123_456_789
424
+ assert ts._value == expected_value
425
+ assert expected_repr in repr(ts)
426
+
427
+ ts = Timestamp("2013-05-01 07:15:45.123456789+09:00", tz="Asia/Tokyo")
428
+ assert ts._value == expected_value - 9 * 3600 * 1_000_000_000
429
+ assert expected_repr in repr(ts)
430
+
431
+ ts = Timestamp("2013-05-01 07:15:45.123456789", tz="UTC")
432
+ assert ts._value == expected_value
433
+ assert expected_repr in repr(ts)
434
+
435
+ ts = Timestamp("2013-05-01 07:15:45.123456789", tz="US/Eastern")
436
+ assert ts._value == expected_value + 4 * 3600 * 1_000_000_000
437
+ assert expected_repr in repr(ts)
438
+
439
+ # GH 10041
440
+ ts = Timestamp("20130501T071545.123456789")
441
+ assert ts._value == expected_value
442
+ assert expected_repr in repr(ts)
443
+
444
+ def test_nanosecond_timestamp(self):
445
+ # GH 7610
446
+ expected = 1_293_840_000_000_000_005
447
+ t = Timestamp("2011-01-01") + offsets.Nano(5)
448
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
449
+ assert t._value == expected
450
+ assert t.nanosecond == 5
451
+
452
+ t = Timestamp(t)
453
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
454
+ assert t._value == expected
455
+ assert t.nanosecond == 5
456
+
457
+ t = Timestamp("2011-01-01 00:00:00.000000005")
458
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000005')"
459
+ assert t._value == expected
460
+ assert t.nanosecond == 5
461
+
462
+ expected = 1_293_840_000_000_000_010
463
+ t = t + offsets.Nano(5)
464
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
465
+ assert t._value == expected
466
+ assert t.nanosecond == 10
467
+
468
+ t = Timestamp(t)
469
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
470
+ assert t._value == expected
471
+ assert t.nanosecond == 10
472
+
473
+ t = Timestamp("2011-01-01 00:00:00.000000010")
474
+ assert repr(t) == "Timestamp('2011-01-01 00:00:00.000000010')"
475
+ assert t._value == expected
476
+ assert t.nanosecond == 10
477
+
478
+
479
+ class TestTimestampConversion:
480
+ def test_conversion(self):
481
+ # GH#9255
482
+ ts = Timestamp("2000-01-01").as_unit("ns")
483
+
484
+ result = ts.to_pydatetime()
485
+ expected = datetime(2000, 1, 1)
486
+ assert result == expected
487
+ assert type(result) == type(expected)
488
+
489
+ result = ts.to_datetime64()
490
+ expected = np.datetime64(ts._value, "ns")
491
+ assert result == expected
492
+ assert type(result) == type(expected)
493
+ assert result.dtype == expected.dtype
494
+
495
+ def test_to_period_tz_warning(self):
496
+ # GH#21333 make sure a warning is issued when timezone
497
+ # info is lost
498
+ ts = Timestamp("2009-04-15 16:17:18", tz="US/Eastern")
499
+ with tm.assert_produces_warning(UserWarning):
500
+ # warning that timezone info will be lost
501
+ ts.to_period("D")
502
+
503
+ def test_to_numpy_alias(self):
504
+ # GH 24653: alias .to_numpy() for scalars
505
+ ts = Timestamp(datetime.now())
506
+ assert ts.to_datetime64() == ts.to_numpy()
507
+
508
+ # GH#44460
509
+ msg = "dtype and copy arguments are ignored"
510
+ with pytest.raises(ValueError, match=msg):
511
+ ts.to_numpy("M8[s]")
512
+ with pytest.raises(ValueError, match=msg):
513
+ ts.to_numpy(copy=True)
514
+
515
+
516
+ class TestNonNano:
517
+ @pytest.fixture(params=["s", "ms", "us"])
518
+ def reso(self, request):
519
+ return request.param
520
+
521
+ @pytest.fixture
522
+ def dt64(self, reso):
523
+ # cases that are in-bounds for nanosecond, so we can compare against
524
+ # the existing implementation.
525
+ return np.datetime64("2016-01-01", reso)
526
+
527
+ @pytest.fixture
528
+ def ts(self, dt64):
529
+ return Timestamp._from_dt64(dt64)
530
+
531
+ @pytest.fixture
532
+ def ts_tz(self, ts, tz_aware_fixture):
533
+ tz = maybe_get_tz(tz_aware_fixture)
534
+ return Timestamp._from_value_and_reso(ts._value, ts._creso, tz)
535
+
536
+ def test_non_nano_construction(self, dt64, ts, reso):
537
+ assert ts._value == dt64.view("i8")
538
+
539
+ if reso == "s":
540
+ assert ts._creso == NpyDatetimeUnit.NPY_FR_s.value
541
+ elif reso == "ms":
542
+ assert ts._creso == NpyDatetimeUnit.NPY_FR_ms.value
543
+ elif reso == "us":
544
+ assert ts._creso == NpyDatetimeUnit.NPY_FR_us.value
545
+
546
+ def test_non_nano_fields(self, dt64, ts):
547
+ alt = Timestamp(dt64)
548
+
549
+ assert ts.year == alt.year
550
+ assert ts.month == alt.month
551
+ assert ts.day == alt.day
552
+ assert ts.hour == ts.minute == ts.second == ts.microsecond == 0
553
+ assert ts.nanosecond == 0
554
+
555
+ assert ts.to_julian_date() == alt.to_julian_date()
556
+ assert ts.weekday() == alt.weekday()
557
+ assert ts.isoweekday() == alt.isoweekday()
558
+
559
+ def test_start_end_fields(self, ts):
560
+ assert ts.is_year_start
561
+ assert ts.is_quarter_start
562
+ assert ts.is_month_start
563
+ assert not ts.is_year_end
564
+ assert not ts.is_month_end
565
+ assert not ts.is_month_end
566
+
567
+ # 2016-01-01 is a Friday, so is year/quarter/month start with this freq
568
+ assert ts.is_year_start
569
+ assert ts.is_quarter_start
570
+ assert ts.is_month_start
571
+ assert not ts.is_year_end
572
+ assert not ts.is_month_end
573
+ assert not ts.is_month_end
574
+
575
+ def test_day_name(self, dt64, ts):
576
+ alt = Timestamp(dt64)
577
+ assert ts.day_name() == alt.day_name()
578
+
579
+ def test_month_name(self, dt64, ts):
580
+ alt = Timestamp(dt64)
581
+ assert ts.month_name() == alt.month_name()
582
+
583
+ def test_tz_convert(self, ts):
584
+ ts = Timestamp._from_value_and_reso(ts._value, ts._creso, utc)
585
+
586
+ tz = pytz.timezone("US/Pacific")
587
+ result = ts.tz_convert(tz)
588
+
589
+ assert isinstance(result, Timestamp)
590
+ assert result._creso == ts._creso
591
+ assert tz_compare(result.tz, tz)
592
+
593
+ def test_repr(self, dt64, ts):
594
+ alt = Timestamp(dt64)
595
+
596
+ assert str(ts) == str(alt)
597
+ assert repr(ts) == repr(alt)
598
+
599
+ def test_comparison(self, dt64, ts):
600
+ alt = Timestamp(dt64)
601
+
602
+ assert ts == dt64
603
+ assert dt64 == ts
604
+ assert ts == alt
605
+ assert alt == ts
606
+
607
+ assert not ts != dt64
608
+ assert not dt64 != ts
609
+ assert not ts != alt
610
+ assert not alt != ts
611
+
612
+ assert not ts < dt64
613
+ assert not dt64 < ts
614
+ assert not ts < alt
615
+ assert not alt < ts
616
+
617
+ assert not ts > dt64
618
+ assert not dt64 > ts
619
+ assert not ts > alt
620
+ assert not alt > ts
621
+
622
+ assert ts >= dt64
623
+ assert dt64 >= ts
624
+ assert ts >= alt
625
+ assert alt >= ts
626
+
627
+ assert ts <= dt64
628
+ assert dt64 <= ts
629
+ assert ts <= alt
630
+ assert alt <= ts
631
+
632
+ def test_cmp_cross_reso(self):
633
+ # numpy gets this wrong because of silent overflow
634
+ dt64 = np.datetime64(9223372800, "s") # won't fit in M8[ns]
635
+ ts = Timestamp._from_dt64(dt64)
636
+
637
+ # subtracting 3600*24 gives a datetime64 that _can_ fit inside the
638
+ # nanosecond implementation bounds.
639
+ other = Timestamp(dt64 - 3600 * 24).as_unit("ns")
640
+ assert other < ts
641
+ assert other.asm8 > ts.asm8 # <- numpy gets this wrong
642
+ assert ts > other
643
+ assert ts.asm8 < other.asm8 # <- numpy gets this wrong
644
+ assert not other == ts
645
+ assert ts != other
646
+
647
+ @pytest.mark.xfail(reason="Dispatches to np.datetime64 which is wrong")
648
+ def test_cmp_cross_reso_reversed_dt64(self):
649
+ dt64 = np.datetime64(106752, "D") # won't fit in M8[ns]
650
+ ts = Timestamp._from_dt64(dt64)
651
+ other = Timestamp(dt64 - 1)
652
+
653
+ assert other.asm8 < ts
654
+
655
+ def test_pickle(self, ts, tz_aware_fixture):
656
+ tz = tz_aware_fixture
657
+ tz = maybe_get_tz(tz)
658
+ ts = Timestamp._from_value_and_reso(ts._value, ts._creso, tz)
659
+ rt = tm.round_trip_pickle(ts)
660
+ assert rt._creso == ts._creso
661
+ assert rt == ts
662
+
663
+ def test_normalize(self, dt64, ts):
664
+ alt = Timestamp(dt64)
665
+ result = ts.normalize()
666
+ assert result._creso == ts._creso
667
+ assert result == alt.normalize()
668
+
669
+ def test_asm8(self, dt64, ts):
670
+ rt = ts.asm8
671
+ assert rt == dt64
672
+ assert rt.dtype == dt64.dtype
673
+
674
+ def test_to_numpy(self, dt64, ts):
675
+ res = ts.to_numpy()
676
+ assert res == dt64
677
+ assert res.dtype == dt64.dtype
678
+
679
+ def test_to_datetime64(self, dt64, ts):
680
+ res = ts.to_datetime64()
681
+ assert res == dt64
682
+ assert res.dtype == dt64.dtype
683
+
684
+ def test_timestamp(self, dt64, ts):
685
+ alt = Timestamp(dt64)
686
+ assert ts.timestamp() == alt.timestamp()
687
+
688
+ def test_to_period(self, dt64, ts):
689
+ alt = Timestamp(dt64)
690
+ assert ts.to_period("D") == alt.to_period("D")
691
+
692
+ @pytest.mark.parametrize(
693
+ "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")]
694
+ )
695
+ def test_addsub_timedeltalike_non_nano(self, dt64, ts, td):
696
+ exp_reso = max(ts._creso, Timedelta(td)._creso)
697
+
698
+ result = ts - td
699
+ expected = Timestamp(dt64) - td
700
+ assert isinstance(result, Timestamp)
701
+ assert result._creso == exp_reso
702
+ assert result == expected
703
+
704
+ result = ts + td
705
+ expected = Timestamp(dt64) + td
706
+ assert isinstance(result, Timestamp)
707
+ assert result._creso == exp_reso
708
+ assert result == expected
709
+
710
+ result = td + ts
711
+ expected = td + Timestamp(dt64)
712
+ assert isinstance(result, Timestamp)
713
+ assert result._creso == exp_reso
714
+ assert result == expected
715
+
716
+ def test_addsub_offset(self, ts_tz):
717
+ # specifically non-Tick offset
718
+ off = offsets.YearEnd(1)
719
+ result = ts_tz + off
720
+
721
+ assert isinstance(result, Timestamp)
722
+ assert result._creso == ts_tz._creso
723
+ if ts_tz.month == 12 and ts_tz.day == 31:
724
+ assert result.year == ts_tz.year + 1
725
+ else:
726
+ assert result.year == ts_tz.year
727
+ assert result.day == 31
728
+ assert result.month == 12
729
+ assert tz_compare(result.tz, ts_tz.tz)
730
+
731
+ result = ts_tz - off
732
+
733
+ assert isinstance(result, Timestamp)
734
+ assert result._creso == ts_tz._creso
735
+ assert result.year == ts_tz.year - 1
736
+ assert result.day == 31
737
+ assert result.month == 12
738
+ assert tz_compare(result.tz, ts_tz.tz)
739
+
740
+ def test_sub_datetimelike_mismatched_reso(self, ts_tz):
741
+ # case with non-lossy rounding
742
+ ts = ts_tz
743
+
744
+ # choose a unit for `other` that doesn't match ts_tz's;
745
+ # this construction ensures we get cases with other._creso < ts._creso
746
+ # and cases with other._creso > ts._creso
747
+ unit = {
748
+ NpyDatetimeUnit.NPY_FR_us.value: "ms",
749
+ NpyDatetimeUnit.NPY_FR_ms.value: "s",
750
+ NpyDatetimeUnit.NPY_FR_s.value: "us",
751
+ }[ts._creso]
752
+ other = ts.as_unit(unit)
753
+ assert other._creso != ts._creso
754
+
755
+ result = ts - other
756
+ assert isinstance(result, Timedelta)
757
+ assert result._value == 0
758
+ assert result._creso == max(ts._creso, other._creso)
759
+
760
+ result = other - ts
761
+ assert isinstance(result, Timedelta)
762
+ assert result._value == 0
763
+ assert result._creso == max(ts._creso, other._creso)
764
+
765
+ if ts._creso < other._creso:
766
+ # Case where rounding is lossy
767
+ other2 = other + Timedelta._from_value_and_reso(1, other._creso)
768
+ exp = ts.as_unit(other.unit) - other2
769
+
770
+ res = ts - other2
771
+ assert res == exp
772
+ assert res._creso == max(ts._creso, other._creso)
773
+
774
+ res = other2 - ts
775
+ assert res == -exp
776
+ assert res._creso == max(ts._creso, other._creso)
777
+ else:
778
+ ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)
779
+ exp = ts2 - other.as_unit(ts2.unit)
780
+
781
+ res = ts2 - other
782
+ assert res == exp
783
+ assert res._creso == max(ts._creso, other._creso)
784
+ res = other - ts2
785
+ assert res == -exp
786
+ assert res._creso == max(ts._creso, other._creso)
787
+
788
+ def test_sub_timedeltalike_mismatched_reso(self, ts_tz):
789
+ # case with non-lossy rounding
790
+ ts = ts_tz
791
+
792
+ # choose a unit for `other` that doesn't match ts_tz's;
793
+ # this construction ensures we get cases with other._creso < ts._creso
794
+ # and cases with other._creso > ts._creso
795
+ unit = {
796
+ NpyDatetimeUnit.NPY_FR_us.value: "ms",
797
+ NpyDatetimeUnit.NPY_FR_ms.value: "s",
798
+ NpyDatetimeUnit.NPY_FR_s.value: "us",
799
+ }[ts._creso]
800
+ other = Timedelta(0).as_unit(unit)
801
+ assert other._creso != ts._creso
802
+
803
+ result = ts + other
804
+ assert isinstance(result, Timestamp)
805
+ assert result == ts
806
+ assert result._creso == max(ts._creso, other._creso)
807
+
808
+ result = other + ts
809
+ assert isinstance(result, Timestamp)
810
+ assert result == ts
811
+ assert result._creso == max(ts._creso, other._creso)
812
+
813
+ if ts._creso < other._creso:
814
+ # Case where rounding is lossy
815
+ other2 = other + Timedelta._from_value_and_reso(1, other._creso)
816
+ exp = ts.as_unit(other.unit) + other2
817
+ res = ts + other2
818
+ assert res == exp
819
+ assert res._creso == max(ts._creso, other._creso)
820
+ res = other2 + ts
821
+ assert res == exp
822
+ assert res._creso == max(ts._creso, other._creso)
823
+ else:
824
+ ts2 = ts + Timedelta._from_value_and_reso(1, ts._creso)
825
+ exp = ts2 + other.as_unit(ts2.unit)
826
+
827
+ res = ts2 + other
828
+ assert res == exp
829
+ assert res._creso == max(ts._creso, other._creso)
830
+ res = other + ts2
831
+ assert res == exp
832
+ assert res._creso == max(ts._creso, other._creso)
833
+
834
+ def test_addition_doesnt_downcast_reso(self):
835
+ # https://github.com/pandas-dev/pandas/pull/48748#pullrequestreview-1122635413
836
+ ts = Timestamp(year=2022, month=1, day=1, microsecond=999999).as_unit("us")
837
+ td = Timedelta(microseconds=1).as_unit("us")
838
+ res = ts + td
839
+ assert res._creso == ts._creso
840
+
841
+ def test_sub_timedelta64_mismatched_reso(self, ts_tz):
842
+ ts = ts_tz
843
+
844
+ res = ts + np.timedelta64(1, "ns")
845
+ exp = ts.as_unit("ns") + np.timedelta64(1, "ns")
846
+ assert exp == res
847
+ assert exp._creso == NpyDatetimeUnit.NPY_FR_ns.value
848
+
849
+ def test_min(self, ts):
850
+ assert ts.min <= ts
851
+ assert ts.min._creso == ts._creso
852
+ assert ts.min._value == NaT._value + 1
853
+
854
+ def test_max(self, ts):
855
+ assert ts.max >= ts
856
+ assert ts.max._creso == ts._creso
857
+ assert ts.max._value == np.iinfo(np.int64).max
858
+
859
+ def test_resolution(self, ts):
860
+ expected = Timedelta._from_value_and_reso(1, ts._creso)
861
+ result = ts.resolution
862
+ assert result == expected
863
+ assert result._creso == expected._creso
864
+
865
+ def test_out_of_ns_bounds(self):
866
+ # https://github.com/pandas-dev/pandas/issues/51060
867
+ result = Timestamp(-52700112000, unit="s")
868
+ assert result == Timestamp("0300-01-01")
869
+ assert result.to_numpy() == np.datetime64("0300-01-01T00:00:00", "s")
870
+
871
+
872
+ def test_timestamp_class_min_max_resolution():
873
+ # when accessed on the class (as opposed to an instance), we default
874
+ # to nanoseconds
875
+ assert Timestamp.min == Timestamp(NaT._value + 1)
876
+ assert Timestamp.min._creso == NpyDatetimeUnit.NPY_FR_ns.value
877
+
878
+ assert Timestamp.max == Timestamp(np.iinfo(np.int64).max)
879
+ assert Timestamp.max._creso == NpyDatetimeUnit.NPY_FR_ns.value
880
+
881
+ assert Timestamp.resolution == Timedelta(1)
882
+ assert Timestamp.resolution._creso == NpyDatetimeUnit.NPY_FR_ns.value
883
+
884
+
885
+ def test_delimited_date():
886
+ # https://github.com/pandas-dev/pandas/issues/50231
887
+ with tm.assert_produces_warning(None):
888
+ result = Timestamp("13-01-2000")
889
+ expected = Timestamp(2000, 1, 13)
890
+ assert result == expected
891
+
892
+
893
+ def test_utctimetuple():
894
+ # GH 32174
895
+ ts = Timestamp("2000-01-01", tz="UTC")
896
+ result = ts.utctimetuple()
897
+ expected = time.struct_time((2000, 1, 1, 0, 0, 0, 5, 1, 0))
898
+ assert result == expected
899
+
900
+
901
+ def test_negative_dates():
902
+ # https://github.com/pandas-dev/pandas/issues/50787
903
+ ts = Timestamp("-2000-01-01")
904
+ msg = (
905
+ " not yet supported on Timestamps which are outside the range of "
906
+ "Python's standard library. For now, please call the components you need "
907
+ r"\(such as `.year` and `.month`\) and construct your string from there.$"
908
+ )
909
+ func = "^strftime"
910
+ with pytest.raises(NotImplementedError, match=func + msg):
911
+ ts.strftime("%Y")
912
+
913
+ msg = (
914
+ " not yet supported on Timestamps which "
915
+ "are outside the range of Python's standard library. "
916
+ )
917
+ func = "^date"
918
+ with pytest.raises(NotImplementedError, match=func + msg):
919
+ ts.date()
920
+ func = "^isocalendar"
921
+ with pytest.raises(NotImplementedError, match=func + msg):
922
+ ts.isocalendar()
923
+ func = "^timetuple"
924
+ with pytest.raises(NotImplementedError, match=func + msg):
925
+ ts.timetuple()
926
+ func = "^toordinal"
927
+ with pytest.raises(NotImplementedError, match=func + msg):
928
+ ts.toordinal()