test_parse_iso8601.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from datetime import datetime
  2. import pytest
  3. from pandas._libs import tslib
  4. from pandas import Timestamp
  5. @pytest.mark.parametrize(
  6. "date_str, exp",
  7. [
  8. ("2011-01-02", datetime(2011, 1, 2)),
  9. ("2011-1-2", datetime(2011, 1, 2)),
  10. ("2011-01", datetime(2011, 1, 1)),
  11. ("2011-1", datetime(2011, 1, 1)),
  12. ("2011 01 02", datetime(2011, 1, 2)),
  13. ("2011.01.02", datetime(2011, 1, 2)),
  14. ("2011/01/02", datetime(2011, 1, 2)),
  15. ("2011\\01\\02", datetime(2011, 1, 2)),
  16. ("2013-01-01 05:30:00", datetime(2013, 1, 1, 5, 30)),
  17. ("2013-1-1 5:30:00", datetime(2013, 1, 1, 5, 30)),
  18. ("2013-1-1 5:30:00+01:00", Timestamp(2013, 1, 1, 5, 30, tz="UTC+01:00")),
  19. ],
  20. )
  21. def test_parsers_iso8601(date_str, exp):
  22. # see gh-12060
  23. #
  24. # Test only the ISO parser - flexibility to
  25. # different separators and leading zero's.
  26. actual = tslib._test_parse_iso8601(date_str)
  27. assert actual == exp
  28. @pytest.mark.parametrize(
  29. "date_str",
  30. [
  31. "2011-01/02",
  32. "2011=11=11",
  33. "201401",
  34. "201111",
  35. "200101",
  36. # Mixed separated and unseparated.
  37. "2005-0101",
  38. "200501-01",
  39. "20010101 12:3456",
  40. "20010101 1234:56",
  41. # HHMMSS must have two digits in
  42. # each component if unseparated.
  43. "20010101 1",
  44. "20010101 123",
  45. "20010101 12345",
  46. "20010101 12345Z",
  47. ],
  48. )
  49. def test_parsers_iso8601_invalid(date_str):
  50. msg = f'Error parsing datetime string "{date_str}"'
  51. with pytest.raises(ValueError, match=msg):
  52. tslib._test_parse_iso8601(date_str)
  53. def test_parsers_iso8601_invalid_offset_invalid():
  54. date_str = "2001-01-01 12-34-56"
  55. msg = f'Timezone hours offset out of range in datetime string "{date_str}"'
  56. with pytest.raises(ValueError, match=msg):
  57. tslib._test_parse_iso8601(date_str)
  58. def test_parsers_iso8601_leading_space():
  59. # GH#25895 make sure isoparser doesn't overflow with long input
  60. date_str, expected = ("2013-1-1 5:30:00", datetime(2013, 1, 1, 5, 30))
  61. actual = tslib._test_parse_iso8601(" " * 200 + date_str)
  62. assert actual == expected