test_arithmetic.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. from datetime import (
  2. datetime,
  3. timedelta,
  4. timezone,
  5. )
  6. import numpy as np
  7. import pytest
  8. from pandas._libs.tslibs import (
  9. OutOfBoundsDatetime,
  10. OutOfBoundsTimedelta,
  11. Timedelta,
  12. Timestamp,
  13. offsets,
  14. to_offset,
  15. )
  16. import pandas._testing as tm
  17. class TestTimestampArithmetic:
  18. def test_overflow_offset(self):
  19. # no overflow expected
  20. stamp = Timestamp("2000/1/1")
  21. offset_no_overflow = to_offset("D") * 100
  22. expected = Timestamp("2000/04/10")
  23. assert stamp + offset_no_overflow == expected
  24. assert offset_no_overflow + stamp == expected
  25. expected = Timestamp("1999/09/23")
  26. assert stamp - offset_no_overflow == expected
  27. def test_overflow_offset_raises(self):
  28. # xref https://github.com/statsmodels/statsmodels/issues/3374
  29. # ends up multiplying really large numbers which overflow
  30. stamp = Timestamp("2017-01-13 00:00:00").as_unit("ns")
  31. offset_overflow = 20169940 * offsets.Day(1)
  32. msg = (
  33. "the add operation between "
  34. r"\<-?\d+ \* Days\> and \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} "
  35. "will overflow"
  36. )
  37. lmsg2 = r"Cannot cast -?20169940 days \+?00:00:00 to unit='ns' without overflow"
  38. with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):
  39. stamp + offset_overflow
  40. with pytest.raises(OverflowError, match=msg):
  41. offset_overflow + stamp
  42. with pytest.raises(OutOfBoundsTimedelta, match=lmsg2):
  43. stamp - offset_overflow
  44. # xref https://github.com/pandas-dev/pandas/issues/14080
  45. # used to crash, so check for proper overflow exception
  46. stamp = Timestamp("2000/1/1").as_unit("ns")
  47. offset_overflow = to_offset("D") * 100**5
  48. lmsg3 = (
  49. r"Cannot cast -?10000000000 days \+?00:00:00 to unit='ns' without overflow"
  50. )
  51. with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):
  52. stamp + offset_overflow
  53. with pytest.raises(OverflowError, match=msg):
  54. offset_overflow + stamp
  55. with pytest.raises(OutOfBoundsTimedelta, match=lmsg3):
  56. stamp - offset_overflow
  57. def test_overflow_timestamp_raises(self):
  58. # https://github.com/pandas-dev/pandas/issues/31774
  59. msg = "Result is too large"
  60. a = Timestamp("2101-01-01 00:00:00").as_unit("ns")
  61. b = Timestamp("1688-01-01 00:00:00").as_unit("ns")
  62. with pytest.raises(OutOfBoundsDatetime, match=msg):
  63. a - b
  64. # but we're OK for timestamp and datetime.datetime
  65. assert (a - b.to_pydatetime()) == (a.to_pydatetime() - b)
  66. def test_delta_preserve_nanos(self):
  67. val = Timestamp(1337299200000000123)
  68. result = val + timedelta(1)
  69. assert result.nanosecond == val.nanosecond
  70. def test_rsub_dtscalars(self, tz_naive_fixture):
  71. # In particular, check that datetime64 - Timestamp works GH#28286
  72. td = Timedelta(1235345642000)
  73. ts = Timestamp("2021-01-01", tz=tz_naive_fixture)
  74. other = ts + td
  75. assert other - ts == td
  76. assert other.to_pydatetime() - ts == td
  77. if tz_naive_fixture is None:
  78. assert other.to_datetime64() - ts == td
  79. else:
  80. msg = "Cannot subtract tz-naive and tz-aware datetime-like objects"
  81. with pytest.raises(TypeError, match=msg):
  82. other.to_datetime64() - ts
  83. def test_timestamp_sub_datetime(self):
  84. dt = datetime(2013, 10, 12)
  85. ts = Timestamp(datetime(2013, 10, 13))
  86. assert (ts - dt).days == 1
  87. assert (dt - ts).days == -1
  88. def test_subtract_tzaware_datetime(self):
  89. t1 = Timestamp("2020-10-22T22:00:00+00:00")
  90. t2 = datetime(2020, 10, 22, 22, tzinfo=timezone.utc)
  91. result = t1 - t2
  92. assert isinstance(result, Timedelta)
  93. assert result == Timedelta("0 days")
  94. def test_subtract_timestamp_from_different_timezone(self):
  95. t1 = Timestamp("20130101").tz_localize("US/Eastern")
  96. t2 = Timestamp("20130101").tz_localize("CET")
  97. result = t1 - t2
  98. assert isinstance(result, Timedelta)
  99. assert result == Timedelta("0 days 06:00:00")
  100. def test_subtracting_involving_datetime_with_different_tz(self):
  101. t1 = datetime(2013, 1, 1, tzinfo=timezone(timedelta(hours=-5)))
  102. t2 = Timestamp("20130101").tz_localize("CET")
  103. result = t1 - t2
  104. assert isinstance(result, Timedelta)
  105. assert result == Timedelta("0 days 06:00:00")
  106. result = t2 - t1
  107. assert isinstance(result, Timedelta)
  108. assert result == Timedelta("-1 days +18:00:00")
  109. def test_subtracting_different_timezones(self, tz_aware_fixture):
  110. t_raw = Timestamp("20130101")
  111. t_UTC = t_raw.tz_localize("UTC")
  112. t_diff = t_UTC.tz_convert(tz_aware_fixture) + Timedelta("0 days 05:00:00")
  113. result = t_diff - t_UTC
  114. assert isinstance(result, Timedelta)
  115. assert result == Timedelta("0 days 05:00:00")
  116. def test_addition_subtraction_types(self):
  117. # Assert on the types resulting from Timestamp +/- various date/time
  118. # objects
  119. dt = datetime(2014, 3, 4)
  120. td = timedelta(seconds=1)
  121. ts = Timestamp(dt)
  122. msg = "Addition/subtraction of integers"
  123. with pytest.raises(TypeError, match=msg):
  124. # GH#22535 add/sub with integers is deprecated
  125. ts + 1
  126. with pytest.raises(TypeError, match=msg):
  127. ts - 1
  128. # Timestamp + datetime not supported, though subtraction is supported
  129. # and yields timedelta more tests in tseries/base/tests/test_base.py
  130. assert type(ts - dt) == Timedelta
  131. assert type(ts + td) == Timestamp
  132. assert type(ts - td) == Timestamp
  133. # Timestamp +/- datetime64 not supported, so not tested (could possibly
  134. # assert error raised?)
  135. td64 = np.timedelta64(1, "D")
  136. assert type(ts + td64) == Timestamp
  137. assert type(ts - td64) == Timestamp
  138. @pytest.mark.parametrize(
  139. "td", [Timedelta(hours=3), np.timedelta64(3, "h"), timedelta(hours=3)]
  140. )
  141. def test_radd_tdscalar(self, td, fixed_now_ts):
  142. # GH#24775 timedelta64+Timestamp should not raise
  143. ts = fixed_now_ts
  144. assert td + ts == ts + td
  145. @pytest.mark.parametrize(
  146. "other,expected_difference",
  147. [
  148. (np.timedelta64(-123, "ns"), -123),
  149. (np.timedelta64(1234567898, "ns"), 1234567898),
  150. (np.timedelta64(-123, "us"), -123000),
  151. (np.timedelta64(-123, "ms"), -123000000),
  152. ],
  153. )
  154. def test_timestamp_add_timedelta64_unit(self, other, expected_difference):
  155. now = datetime.utcnow()
  156. ts = Timestamp(now).as_unit("ns")
  157. result = ts + other
  158. valdiff = result._value - ts._value
  159. assert valdiff == expected_difference
  160. ts2 = Timestamp(now)
  161. assert ts2 + other == result
  162. @pytest.mark.parametrize(
  163. "ts",
  164. [
  165. Timestamp("1776-07-04"),
  166. Timestamp("1776-07-04", tz="UTC"),
  167. ],
  168. )
  169. @pytest.mark.parametrize(
  170. "other",
  171. [
  172. 1,
  173. np.int64(1),
  174. np.array([1, 2], dtype=np.int32),
  175. np.array([3, 4], dtype=np.uint64),
  176. ],
  177. )
  178. def test_add_int_with_freq(self, ts, other):
  179. msg = "Addition/subtraction of integers and integer-arrays"
  180. with pytest.raises(TypeError, match=msg):
  181. ts + other
  182. with pytest.raises(TypeError, match=msg):
  183. other + ts
  184. with pytest.raises(TypeError, match=msg):
  185. ts - other
  186. msg = "unsupported operand type"
  187. with pytest.raises(TypeError, match=msg):
  188. other - ts
  189. @pytest.mark.parametrize("shape", [(6,), (2, 3)])
  190. def test_addsub_m8ndarray(self, shape):
  191. # GH#33296
  192. ts = Timestamp("2020-04-04 15:45").as_unit("ns")
  193. other = np.arange(6).astype("m8[h]").reshape(shape)
  194. result = ts + other
  195. ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]
  196. expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)
  197. tm.assert_numpy_array_equal(result, expected)
  198. result = other + ts
  199. tm.assert_numpy_array_equal(result, expected)
  200. result = ts - other
  201. ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]
  202. expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape)
  203. tm.assert_numpy_array_equal(result, expected)
  204. msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"
  205. with pytest.raises(TypeError, match=msg):
  206. other - ts
  207. @pytest.mark.parametrize("shape", [(6,), (2, 3)])
  208. def test_addsub_m8ndarray_tzaware(self, shape):
  209. # GH#33296
  210. ts = Timestamp("2020-04-04 15:45", tz="US/Pacific")
  211. other = np.arange(6).astype("m8[h]").reshape(shape)
  212. result = ts + other
  213. ex_stamps = [ts + Timedelta(hours=n) for n in range(6)]
  214. expected = np.array(ex_stamps).reshape(shape)
  215. tm.assert_numpy_array_equal(result, expected)
  216. result = other + ts
  217. tm.assert_numpy_array_equal(result, expected)
  218. result = ts - other
  219. ex_stamps = [ts - Timedelta(hours=n) for n in range(6)]
  220. expected = np.array(ex_stamps).reshape(shape)
  221. tm.assert_numpy_array_equal(result, expected)
  222. msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'"
  223. with pytest.raises(TypeError, match=msg):
  224. other - ts
  225. def test_subtract_different_utc_objects(self, utc_fixture, utc_fixture2):
  226. # GH 32619
  227. dt = datetime(2021, 1, 1)
  228. ts1 = Timestamp(dt, tz=utc_fixture)
  229. ts2 = Timestamp(dt, tz=utc_fixture2)
  230. result = ts1 - ts2
  231. expected = Timedelta(0)
  232. assert result == expected