test_datetime.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """
  2. This file contains a minimal set of tests for compliance with the extension
  3. array interface test suite, and should contain no other tests.
  4. The test suite for the full functionality of the array is located in
  5. `pandas/tests/arrays/`.
  6. The tests in this file are inherited from the BaseExtensionTests, and only
  7. minimal tweaks should be applied to get the tests passing (by overwriting a
  8. parent method).
  9. Additional tests should either be added to one of the BaseExtensionTests
  10. classes (if they are relevant for the extension interface for all dtypes), or
  11. be added to the array-specific tests in `pandas/tests/arrays/`.
  12. """
  13. import numpy as np
  14. import pytest
  15. from pandas.core.dtypes.dtypes import DatetimeTZDtype
  16. import pandas as pd
  17. import pandas._testing as tm
  18. from pandas.core.arrays import DatetimeArray
  19. from pandas.tests.extension import base
  20. @pytest.fixture(params=["US/Central"])
  21. def dtype(request):
  22. return DatetimeTZDtype(unit="ns", tz=request.param)
  23. @pytest.fixture
  24. def data(dtype):
  25. data = DatetimeArray._from_sequence(
  26. pd.date_range("2000", periods=100, tz=dtype.tz), dtype=dtype
  27. )
  28. return data
  29. @pytest.fixture
  30. def data_missing(dtype):
  31. return DatetimeArray._from_sequence(
  32. np.array(["NaT", "2000-01-01"], dtype="datetime64[ns]"), dtype=dtype
  33. )
  34. @pytest.fixture
  35. def data_for_sorting(dtype):
  36. a = pd.Timestamp("2000-01-01")
  37. b = pd.Timestamp("2000-01-02")
  38. c = pd.Timestamp("2000-01-03")
  39. return DatetimeArray._from_sequence(
  40. np.array([b, c, a], dtype="datetime64[ns]"), dtype=dtype
  41. )
  42. @pytest.fixture
  43. def data_missing_for_sorting(dtype):
  44. a = pd.Timestamp("2000-01-01")
  45. b = pd.Timestamp("2000-01-02")
  46. return DatetimeArray._from_sequence(
  47. np.array([b, "NaT", a], dtype="datetime64[ns]"), dtype=dtype
  48. )
  49. @pytest.fixture
  50. def data_for_grouping(dtype):
  51. """
  52. Expected to be like [B, B, NA, NA, A, A, B, C]
  53. Where A < B < C and NA is missing
  54. """
  55. a = pd.Timestamp("2000-01-01")
  56. b = pd.Timestamp("2000-01-02")
  57. c = pd.Timestamp("2000-01-03")
  58. na = "NaT"
  59. return DatetimeArray._from_sequence(
  60. np.array([b, b, na, na, a, a, b, c], dtype="datetime64[ns]"), dtype=dtype
  61. )
  62. @pytest.fixture
  63. def na_cmp():
  64. def cmp(a, b):
  65. return a is pd.NaT and a is b
  66. return cmp
  67. # ----------------------------------------------------------------------------
  68. class TestDatetimeArray(base.ExtensionTests):
  69. def _get_expected_exception(self, op_name, obj, other):
  70. if op_name in ["__sub__", "__rsub__"]:
  71. return None
  72. return super()._get_expected_exception(op_name, obj, other)
  73. def _supports_accumulation(self, ser, op_name: str) -> bool:
  74. return op_name in ["cummin", "cummax"]
  75. def _supports_reduction(self, obj, op_name: str) -> bool:
  76. return op_name in ["min", "max", "median", "mean", "std", "any", "all"]
  77. @pytest.mark.parametrize("skipna", [True, False])
  78. def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
  79. meth = all_boolean_reductions
  80. msg = f"'{meth}' with datetime64 dtypes is deprecated and will raise in"
  81. with tm.assert_produces_warning(
  82. FutureWarning, match=msg, check_stacklevel=False
  83. ):
  84. super().test_reduce_series_boolean(data, all_boolean_reductions, skipna)
  85. def test_series_constructor(self, data):
  86. # Series construction drops any .freq attr
  87. data = data._with_freq(None)
  88. super().test_series_constructor(data)
  89. @pytest.mark.parametrize("na_action", [None, "ignore"])
  90. def test_map(self, data, na_action):
  91. result = data.map(lambda x: x, na_action=na_action)
  92. tm.assert_extension_array_equal(result, data)
  93. def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
  94. if op_name in ["median", "mean", "std"]:
  95. alt = ser.astype("int64")
  96. res_op = getattr(ser, op_name)
  97. exp_op = getattr(alt, op_name)
  98. result = res_op(skipna=skipna)
  99. expected = exp_op(skipna=skipna)
  100. if op_name in ["mean", "median"]:
  101. # error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype"
  102. # has no attribute "tz"
  103. tz = ser.dtype.tz # type: ignore[union-attr]
  104. expected = pd.Timestamp(expected, tz=tz)
  105. else:
  106. expected = pd.Timedelta(expected)
  107. tm.assert_almost_equal(result, expected)
  108. else:
  109. return super().check_reduce(ser, op_name, skipna)
  110. class Test2DCompat(base.NDArrayBacked2DTests):
  111. pass