test_freq_code.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import numpy as np
  2. import pytest
  3. from pandas._libs.tslibs import (
  4. Period,
  5. Resolution,
  6. to_offset,
  7. )
  8. from pandas._libs.tslibs.dtypes import _attrname_to_abbrevs
  9. @pytest.mark.parametrize(
  10. "freqstr,exp_freqstr",
  11. [("D", "D"), ("W", "D"), ("M", "D"), ("S", "S"), ("T", "S"), ("H", "S")],
  12. )
  13. def test_get_to_timestamp_base(freqstr, exp_freqstr):
  14. off = to_offset(freqstr)
  15. per = Period._from_ordinal(1, off)
  16. exp_code = to_offset(exp_freqstr)._period_dtype_code
  17. result_code = per._dtype._get_to_timestamp_base()
  18. assert result_code == exp_code
  19. @pytest.mark.parametrize(
  20. "freqstr,expected",
  21. [
  22. ("A", "year"),
  23. ("Q", "quarter"),
  24. ("M", "month"),
  25. ("D", "day"),
  26. ("H", "hour"),
  27. ("T", "minute"),
  28. ("S", "second"),
  29. ("L", "millisecond"),
  30. ("U", "microsecond"),
  31. ("N", "nanosecond"),
  32. ],
  33. )
  34. def test_get_attrname_from_abbrev(freqstr, expected):
  35. assert Resolution.get_reso_from_freqstr(freqstr).attrname == expected
  36. @pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U", "N"])
  37. def test_get_freq_roundtrip2(freq):
  38. obj = Resolution.get_reso_from_freqstr(freq)
  39. result = _attrname_to_abbrevs[obj.attrname]
  40. assert freq == result
  41. @pytest.mark.parametrize(
  42. "args,expected",
  43. [
  44. ((1.5, "T"), (90, "S")),
  45. ((62.4, "T"), (3744, "S")),
  46. ((1.04, "H"), (3744, "S")),
  47. ((1, "D"), (1, "D")),
  48. ((0.342931, "H"), (1234551600, "U")),
  49. ((1.2345, "D"), (106660800, "L")),
  50. ],
  51. )
  52. def test_resolution_bumping(args, expected):
  53. # see gh-14378
  54. off = to_offset(str(args[0]) + args[1])
  55. assert off.n == expected[0]
  56. assert off._prefix == expected[1]
  57. @pytest.mark.parametrize(
  58. "args",
  59. [
  60. (0.5, "N"),
  61. # Too much precision in the input can prevent.
  62. (0.3429324798798269273987982, "H"),
  63. ],
  64. )
  65. def test_cat(args):
  66. msg = "Invalid frequency"
  67. with pytest.raises(ValueError, match=msg):
  68. to_offset(str(args[0]) + args[1])
  69. @pytest.mark.parametrize(
  70. "freqstr,expected",
  71. [
  72. ("1H", "2021-01-01T09:00:00"),
  73. ("1D", "2021-01-02T08:00:00"),
  74. ("1W", "2021-01-03T08:00:00"),
  75. ("1M", "2021-01-31T08:00:00"),
  76. ("1Y", "2021-12-31T08:00:00"),
  77. ],
  78. )
  79. def test_compatibility(freqstr, expected):
  80. ts_np = np.datetime64("2021-01-01T08:00:00.00")
  81. do = to_offset(freqstr)
  82. assert ts_np + do == np.datetime64(expected)