test_to_timedelta.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. from datetime import (
  2. time,
  3. timedelta,
  4. )
  5. import numpy as np
  6. import pytest
  7. from pandas.errors import OutOfBoundsTimedelta
  8. import pandas as pd
  9. from pandas import (
  10. Series,
  11. TimedeltaIndex,
  12. isna,
  13. to_timedelta,
  14. )
  15. import pandas._testing as tm
  16. from pandas.core.arrays import TimedeltaArray
  17. class TestTimedeltas:
  18. @pytest.mark.parametrize("readonly", [True, False])
  19. def test_to_timedelta_readonly(self, readonly):
  20. # GH#34857
  21. arr = np.array([], dtype=object)
  22. if readonly:
  23. arr.setflags(write=False)
  24. result = to_timedelta(arr)
  25. expected = to_timedelta([])
  26. tm.assert_index_equal(result, expected)
  27. def test_to_timedelta_null(self):
  28. result = to_timedelta(["", ""])
  29. assert isna(result).all()
  30. def test_to_timedelta_same_np_timedelta64(self):
  31. # pass thru
  32. result = to_timedelta(np.array([np.timedelta64(1, "s")]))
  33. expected = pd.Index(np.array([np.timedelta64(1, "s")]))
  34. tm.assert_index_equal(result, expected)
  35. def test_to_timedelta_series(self):
  36. # Series
  37. expected = Series([timedelta(days=1), timedelta(days=1, seconds=1)])
  38. result = to_timedelta(Series(["1d", "1days 00:00:01"]))
  39. tm.assert_series_equal(result, expected)
  40. def test_to_timedelta_units(self):
  41. # with units
  42. result = TimedeltaIndex(
  43. [np.timedelta64(0, "ns"), np.timedelta64(10, "s").astype("m8[ns]")]
  44. )
  45. expected = to_timedelta([0, 10], unit="s")
  46. tm.assert_index_equal(result, expected)
  47. @pytest.mark.parametrize(
  48. "dtype, unit",
  49. [
  50. ["int64", "s"],
  51. ["int64", "m"],
  52. ["int64", "h"],
  53. ["timedelta64[s]", "s"],
  54. ["timedelta64[D]", "D"],
  55. ],
  56. )
  57. def test_to_timedelta_units_dtypes(self, dtype, unit):
  58. # arrays of various dtypes
  59. arr = np.array([1] * 5, dtype=dtype)
  60. result = to_timedelta(arr, unit=unit)
  61. exp_dtype = "m8[ns]" if dtype == "int64" else "m8[s]"
  62. expected = TimedeltaIndex([np.timedelta64(1, unit)] * 5, dtype=exp_dtype)
  63. tm.assert_index_equal(result, expected)
  64. def test_to_timedelta_oob_non_nano(self):
  65. arr = np.array([pd.NaT._value + 1], dtype="timedelta64[m]")
  66. msg = (
  67. "Cannot convert -9223372036854775807 minutes to "
  68. r"timedelta64\[s\] without overflow"
  69. )
  70. with pytest.raises(OutOfBoundsTimedelta, match=msg):
  71. to_timedelta(arr)
  72. with pytest.raises(OutOfBoundsTimedelta, match=msg):
  73. TimedeltaIndex(arr)
  74. with pytest.raises(OutOfBoundsTimedelta, match=msg):
  75. TimedeltaArray._from_sequence(arr)
  76. @pytest.mark.parametrize(
  77. "arg", [np.arange(10).reshape(2, 5), pd.DataFrame(np.arange(10).reshape(2, 5))]
  78. )
  79. @pytest.mark.parametrize("errors", ["ignore", "raise", "coerce"])
  80. def test_to_timedelta_dataframe(self, arg, errors):
  81. # GH 11776
  82. with pytest.raises(TypeError, match="1-d array"):
  83. to_timedelta(arg, errors=errors)
  84. def test_to_timedelta_invalid_errors(self):
  85. # bad value for errors parameter
  86. msg = "errors must be one of"
  87. with pytest.raises(ValueError, match=msg):
  88. to_timedelta(["foo"], errors="never")
  89. @pytest.mark.parametrize("arg", [[1, 2], 1])
  90. def test_to_timedelta_invalid_unit(self, arg):
  91. # these will error
  92. msg = "invalid unit abbreviation: foo"
  93. with pytest.raises(ValueError, match=msg):
  94. to_timedelta(arg, unit="foo")
  95. def test_to_timedelta_time(self):
  96. # time not supported ATM
  97. msg = (
  98. "Value must be Timedelta, string, integer, float, timedelta or convertible"
  99. )
  100. with pytest.raises(ValueError, match=msg):
  101. to_timedelta(time(second=1))
  102. assert to_timedelta(time(second=1), errors="coerce") is pd.NaT
  103. def test_to_timedelta_bad_value(self):
  104. msg = "Could not convert 'foo' to NumPy timedelta"
  105. with pytest.raises(ValueError, match=msg):
  106. to_timedelta(["foo", "bar"])
  107. def test_to_timedelta_bad_value_coerce(self):
  108. tm.assert_index_equal(
  109. TimedeltaIndex([pd.NaT, pd.NaT]),
  110. to_timedelta(["foo", "bar"], errors="coerce"),
  111. )
  112. tm.assert_index_equal(
  113. TimedeltaIndex(["1 day", pd.NaT, "1 min"]),
  114. to_timedelta(["1 day", "bar", "1 min"], errors="coerce"),
  115. )
  116. def test_to_timedelta_invalid_errors_ignore(self):
  117. # gh-13613: these should not error because errors='ignore'
  118. invalid_data = "apple"
  119. assert invalid_data == to_timedelta(invalid_data, errors="ignore")
  120. invalid_data = ["apple", "1 days"]
  121. tm.assert_numpy_array_equal(
  122. np.array(invalid_data, dtype=object),
  123. to_timedelta(invalid_data, errors="ignore"),
  124. )
  125. invalid_data = pd.Index(["apple", "1 days"])
  126. tm.assert_index_equal(invalid_data, to_timedelta(invalid_data, errors="ignore"))
  127. invalid_data = Series(["apple", "1 days"])
  128. tm.assert_series_equal(
  129. invalid_data, to_timedelta(invalid_data, errors="ignore")
  130. )
  131. @pytest.mark.parametrize(
  132. "val, errors",
  133. [
  134. ("1M", True),
  135. ("1 M", True),
  136. ("1Y", True),
  137. ("1 Y", True),
  138. ("1y", True),
  139. ("1 y", True),
  140. ("1m", False),
  141. ("1 m", False),
  142. ("1 day", False),
  143. ("2day", False),
  144. ],
  145. )
  146. def test_unambiguous_timedelta_values(self, val, errors):
  147. # GH36666 Deprecate use of strings denoting units with 'M', 'Y', 'm' or 'y'
  148. # in pd.to_timedelta
  149. msg = "Units 'M', 'Y' and 'y' do not represent unambiguous timedelta"
  150. if errors:
  151. with pytest.raises(ValueError, match=msg):
  152. to_timedelta(val)
  153. else:
  154. # check it doesn't raise
  155. to_timedelta(val)
  156. def test_to_timedelta_via_apply(self):
  157. # GH 5458
  158. expected = Series([np.timedelta64(1, "s")])
  159. result = Series(["00:00:01"]).apply(to_timedelta)
  160. tm.assert_series_equal(result, expected)
  161. result = Series([to_timedelta("00:00:01")])
  162. tm.assert_series_equal(result, expected)
  163. def test_to_timedelta_inference_without_warning(self):
  164. # GH#41731 inference produces a warning in the Series constructor,
  165. # but _not_ in to_timedelta
  166. vals = ["00:00:01", pd.NaT]
  167. with tm.assert_produces_warning(None):
  168. result = to_timedelta(vals)
  169. expected = TimedeltaIndex([pd.Timedelta(seconds=1), pd.NaT])
  170. tm.assert_index_equal(result, expected)
  171. def test_to_timedelta_on_missing_values(self):
  172. # GH5438
  173. timedelta_NaT = np.timedelta64("NaT")
  174. actual = to_timedelta(Series(["00:00:01", np.nan]))
  175. expected = Series(
  176. [np.timedelta64(1000000000, "ns"), timedelta_NaT],
  177. dtype=f"{tm.ENDIAN}m8[ns]",
  178. )
  179. tm.assert_series_equal(actual, expected)
  180. ser = Series(["00:00:01", pd.NaT], dtype="m8[ns]")
  181. actual = to_timedelta(ser)
  182. tm.assert_series_equal(actual, expected)
  183. @pytest.mark.parametrize("val", [np.nan, pd.NaT])
  184. def test_to_timedelta_on_missing_values_scalar(self, val):
  185. actual = to_timedelta(val)
  186. assert actual._value == np.timedelta64("NaT").astype("int64")
  187. def test_to_timedelta_float(self):
  188. # https://github.com/pandas-dev/pandas/issues/25077
  189. arr = np.arange(0, 1, 1e-6)[-10:]
  190. result = to_timedelta(arr, unit="s")
  191. expected_asi8 = np.arange(999990000, 10**9, 1000, dtype="int64")
  192. tm.assert_numpy_array_equal(result.asi8, expected_asi8)
  193. def test_to_timedelta_coerce_strings_unit(self):
  194. arr = np.array([1, 2, "error"], dtype=object)
  195. result = to_timedelta(arr, unit="ns", errors="coerce")
  196. expected = to_timedelta([1, 2, pd.NaT], unit="ns")
  197. tm.assert_index_equal(result, expected)
  198. def test_to_timedelta_ignore_strings_unit(self):
  199. arr = np.array([1, 2, "error"], dtype=object)
  200. result = to_timedelta(arr, unit="ns", errors="ignore")
  201. tm.assert_numpy_array_equal(result, arr)
  202. @pytest.mark.parametrize(
  203. "expected_val, result_val", [[timedelta(days=2), 2], [None, None]]
  204. )
  205. def test_to_timedelta_nullable_int64_dtype(self, expected_val, result_val):
  206. # GH 35574
  207. expected = Series([timedelta(days=1), expected_val])
  208. result = to_timedelta(Series([1, result_val], dtype="Int64"), unit="days")
  209. tm.assert_series_equal(result, expected)
  210. @pytest.mark.parametrize(
  211. ("input", "expected"),
  212. [
  213. ("8:53:08.71800000001", "8:53:08.718"),
  214. ("8:53:08.718001", "8:53:08.718001"),
  215. ("8:53:08.7180000001", "8:53:08.7180000001"),
  216. ("-8:53:08.71800000001", "-8:53:08.718"),
  217. ("8:53:08.7180000089", "8:53:08.718000008"),
  218. ],
  219. )
  220. @pytest.mark.parametrize("func", [pd.Timedelta, to_timedelta])
  221. def test_to_timedelta_precision_over_nanos(self, input, expected, func):
  222. # GH: 36738
  223. expected = pd.Timedelta(expected)
  224. result = func(input)
  225. assert result == expected
  226. def test_to_timedelta_zerodim(self, fixed_now_ts):
  227. # ndarray.item() incorrectly returns int for dt64[ns] and td64[ns]
  228. dt64 = fixed_now_ts.to_datetime64()
  229. arg = np.array(dt64)
  230. msg = (
  231. "Value must be Timedelta, string, integer, float, timedelta "
  232. "or convertible, not datetime64"
  233. )
  234. with pytest.raises(ValueError, match=msg):
  235. to_timedelta(arg)
  236. arg2 = arg.view("m8[ns]")
  237. result = to_timedelta(arg2)
  238. assert isinstance(result, pd.Timedelta)
  239. assert result._value == dt64.view("i8")
  240. def test_to_timedelta_numeric_ea(self, any_numeric_ea_dtype):
  241. # GH#48796
  242. ser = Series([1, pd.NA], dtype=any_numeric_ea_dtype)
  243. result = to_timedelta(ser)
  244. expected = Series([pd.Timedelta(1, unit="ns"), pd.NaT])
  245. tm.assert_series_equal(result, expected)
  246. def test_from_numeric_arrow_dtype(any_numeric_ea_dtype):
  247. # GH 52425
  248. pytest.importorskip("pyarrow")
  249. ser = Series([1, 2], dtype=f"{any_numeric_ea_dtype.lower()}[pyarrow]")
  250. result = to_timedelta(ser)
  251. expected = Series([1, 2], dtype="timedelta64[ns]")
  252. tm.assert_series_equal(result, expected)