test_freq_attr.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import pytest
  2. from pandas import (
  3. DatetimeIndex,
  4. date_range,
  5. )
  6. from pandas.tseries.offsets import (
  7. BDay,
  8. DateOffset,
  9. Day,
  10. Hour,
  11. )
  12. class TestFreq:
  13. def test_freq_setter_errors(self):
  14. # GH#20678
  15. idx = DatetimeIndex(["20180101", "20180103", "20180105"])
  16. # setting with an incompatible freq
  17. msg = (
  18. "Inferred frequency 2D from passed values does not conform to "
  19. "passed frequency 5D"
  20. )
  21. with pytest.raises(ValueError, match=msg):
  22. idx._data.freq = "5D"
  23. # setting with non-freq string
  24. with pytest.raises(ValueError, match="Invalid frequency"):
  25. idx._data.freq = "foo"
  26. @pytest.mark.parametrize("values", [["20180101", "20180103", "20180105"], []])
  27. @pytest.mark.parametrize("freq", ["2D", Day(2), "2B", BDay(2), "48H", Hour(48)])
  28. @pytest.mark.parametrize("tz", [None, "US/Eastern"])
  29. def test_freq_setter(self, values, freq, tz):
  30. # GH#20678
  31. idx = DatetimeIndex(values, tz=tz)
  32. # can set to an offset, converting from string if necessary
  33. idx._data.freq = freq
  34. assert idx.freq == freq
  35. assert isinstance(idx.freq, DateOffset)
  36. # can reset to None
  37. idx._data.freq = None
  38. assert idx.freq is None
  39. def test_freq_view_safe(self):
  40. # Setting the freq for one DatetimeIndex shouldn't alter the freq
  41. # for another that views the same data
  42. dti = date_range("2016-01-01", periods=5)
  43. dta = dti._data
  44. dti2 = DatetimeIndex(dta)._with_freq(None)
  45. assert dti2.freq is None
  46. # Original was not altered
  47. assert dti.freq == "D"
  48. assert dta.freq == "D"