test_to_time.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from datetime import time
  2. import locale
  3. import numpy as np
  4. import pytest
  5. from pandas.compat import PY311
  6. from pandas import Series
  7. import pandas._testing as tm
  8. from pandas.core.tools.times import to_time
  9. # The tests marked with this are locale-dependent.
  10. # They pass, except when the machine locale is zh_CN or it_IT.
  11. fails_on_non_english = pytest.mark.xfail(
  12. locale.getlocale()[0] in ("zh_CN", "it_IT"),
  13. reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8",
  14. strict=False,
  15. )
  16. class TestToTime:
  17. @pytest.mark.parametrize(
  18. "time_string",
  19. [
  20. "14:15",
  21. "1415",
  22. pytest.param("2:15pm", marks=fails_on_non_english),
  23. pytest.param("0215pm", marks=fails_on_non_english),
  24. "14:15:00",
  25. "141500",
  26. pytest.param("2:15:00pm", marks=fails_on_non_english),
  27. pytest.param("021500pm", marks=fails_on_non_english),
  28. time(14, 15),
  29. ],
  30. )
  31. def test_parsers_time(self, time_string):
  32. # GH#11818
  33. assert to_time(time_string) == time(14, 15)
  34. def test_odd_format(self):
  35. new_string = "14.15"
  36. msg = r"Cannot convert arg \['14\.15'\] to a time"
  37. if not PY311:
  38. with pytest.raises(ValueError, match=msg):
  39. to_time(new_string)
  40. assert to_time(new_string, format="%H.%M") == time(14, 15)
  41. def test_arraylike(self):
  42. arg = ["14:15", "20:20"]
  43. expected_arr = [time(14, 15), time(20, 20)]
  44. assert to_time(arg) == expected_arr
  45. assert to_time(arg, format="%H:%M") == expected_arr
  46. assert to_time(arg, infer_time_format=True) == expected_arr
  47. assert to_time(arg, format="%I:%M%p", errors="coerce") == [None, None]
  48. res = to_time(arg, format="%I:%M%p", errors="ignore")
  49. tm.assert_numpy_array_equal(res, np.array(arg, dtype=np.object_))
  50. msg = "Cannot convert.+to a time with given format"
  51. with pytest.raises(ValueError, match=msg):
  52. to_time(arg, format="%I:%M%p", errors="raise")
  53. tm.assert_series_equal(
  54. to_time(Series(arg, name="test")), Series(expected_arr, name="test")
  55. )
  56. res = to_time(np.array(arg))
  57. assert isinstance(res, list)
  58. assert res == expected_arr