test_parsing.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. """
  2. Tests for Timestamp parsing, aimed at pandas/_libs/tslibs/parsing.pyx
  3. """
  4. from datetime import datetime
  5. import re
  6. from dateutil.parser import parse as du_parse
  7. from dateutil.tz import tzlocal
  8. import numpy as np
  9. import pytest
  10. from pandas._libs.tslibs import (
  11. parsing,
  12. strptime,
  13. )
  14. from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso
  15. import pandas.util._test_decorators as td
  16. import pandas._testing as tm
  17. @td.skip_if_windows
  18. def test_parsing_tzlocal_deprecated():
  19. # GH#50791
  20. msg = "Pass the 'tz' keyword or call tz_localize after construction instead"
  21. dtstr = "Jan 15 2004 03:00 EST"
  22. with tm.set_timezone("US/Eastern"):
  23. with tm.assert_produces_warning(FutureWarning, match=msg):
  24. res, _ = parse_datetime_string_with_reso(dtstr)
  25. assert isinstance(res.tzinfo, tzlocal)
  26. with tm.assert_produces_warning(FutureWarning, match=msg):
  27. res = parsing.py_parse_datetime_string(dtstr)
  28. assert isinstance(res.tzinfo, tzlocal)
  29. def test_parse_datetime_string_with_reso():
  30. (parsed, reso) = parse_datetime_string_with_reso("4Q1984")
  31. (parsed_lower, reso_lower) = parse_datetime_string_with_reso("4q1984")
  32. assert reso == reso_lower
  33. assert parsed == parsed_lower
  34. def test_parse_datetime_string_with_reso_nanosecond_reso():
  35. # GH#46811
  36. parsed, reso = parse_datetime_string_with_reso("2022-04-20 09:19:19.123456789")
  37. assert reso == "nanosecond"
  38. def test_parse_datetime_string_with_reso_invalid_type():
  39. # Raise on invalid input, don't just return it
  40. msg = "Argument 'date_string' has incorrect type (expected str, got tuple)"
  41. with pytest.raises(TypeError, match=re.escape(msg)):
  42. parse_datetime_string_with_reso((4, 5))
  43. @pytest.mark.parametrize(
  44. "dashed,normal", [("1988-Q2", "1988Q2"), ("2Q-1988", "2Q1988")]
  45. )
  46. def test_parse_time_quarter_with_dash(dashed, normal):
  47. # see gh-9688
  48. (parsed_dash, reso_dash) = parse_datetime_string_with_reso(dashed)
  49. (parsed, reso) = parse_datetime_string_with_reso(normal)
  50. assert parsed_dash == parsed
  51. assert reso_dash == reso
  52. @pytest.mark.parametrize("dashed", ["-2Q1992", "2-Q1992", "4-4Q1992"])
  53. def test_parse_time_quarter_with_dash_error(dashed):
  54. msg = f"Unknown datetime string format, unable to parse: {dashed}"
  55. with pytest.raises(parsing.DateParseError, match=msg):
  56. parse_datetime_string_with_reso(dashed)
  57. @pytest.mark.parametrize(
  58. "date_string,expected",
  59. [
  60. ("123.1234", False),
  61. ("-50000", False),
  62. ("999", False),
  63. ("m", False),
  64. ("T", False),
  65. ("Mon Sep 16, 2013", True),
  66. ("2012-01-01", True),
  67. ("01/01/2012", True),
  68. ("01012012", True),
  69. ("0101", True),
  70. ("1-1", True),
  71. ],
  72. )
  73. def test_does_not_convert_mixed_integer(date_string, expected):
  74. assert parsing._does_string_look_like_datetime(date_string) is expected
  75. @pytest.mark.parametrize(
  76. "date_str,kwargs,msg",
  77. [
  78. (
  79. "2013Q5",
  80. {},
  81. (
  82. "Incorrect quarterly string is given, "
  83. "quarter must be between 1 and 4: 2013Q5"
  84. ),
  85. ),
  86. # see gh-5418
  87. (
  88. "2013Q1",
  89. {"freq": "INVLD-L-DEC-SAT"},
  90. (
  91. "Unable to retrieve month information "
  92. "from given freq: INVLD-L-DEC-SAT"
  93. ),
  94. ),
  95. ],
  96. )
  97. def test_parsers_quarterly_with_freq_error(date_str, kwargs, msg):
  98. with pytest.raises(parsing.DateParseError, match=msg):
  99. parsing.parse_datetime_string_with_reso(date_str, **kwargs)
  100. @pytest.mark.parametrize(
  101. "date_str,freq,expected",
  102. [
  103. ("2013Q2", None, datetime(2013, 4, 1)),
  104. ("2013Q2", "A-APR", datetime(2012, 8, 1)),
  105. ("2013-Q2", "A-DEC", datetime(2013, 4, 1)),
  106. ],
  107. )
  108. def test_parsers_quarterly_with_freq(date_str, freq, expected):
  109. result, _ = parsing.parse_datetime_string_with_reso(date_str, freq=freq)
  110. assert result == expected
  111. @pytest.mark.parametrize(
  112. "date_str", ["2Q 2005", "2Q-200A", "2Q-200", "22Q2005", "2Q200.", "6Q-20"]
  113. )
  114. def test_parsers_quarter_invalid(date_str):
  115. if date_str == "6Q-20":
  116. msg = (
  117. "Incorrect quarterly string is given, quarter "
  118. f"must be between 1 and 4: {date_str}"
  119. )
  120. else:
  121. msg = f"Unknown datetime string format, unable to parse: {date_str}"
  122. with pytest.raises(ValueError, match=msg):
  123. parsing.parse_datetime_string_with_reso(date_str)
  124. @pytest.mark.parametrize(
  125. "date_str,expected",
  126. [("201101", datetime(2011, 1, 1, 0, 0)), ("200005", datetime(2000, 5, 1, 0, 0))],
  127. )
  128. def test_parsers_month_freq(date_str, expected):
  129. result, _ = parsing.parse_datetime_string_with_reso(date_str, freq="M")
  130. assert result == expected
  131. @td.skip_if_not_us_locale
  132. @pytest.mark.parametrize(
  133. "string,fmt",
  134. [
  135. ("20111230", "%Y%m%d"),
  136. ("201112300000", "%Y%m%d%H%M"),
  137. ("20111230000000", "%Y%m%d%H%M%S"),
  138. ("20111230T00", "%Y%m%dT%H"),
  139. ("20111230T0000", "%Y%m%dT%H%M"),
  140. ("20111230T000000", "%Y%m%dT%H%M%S"),
  141. ("2011-12-30", "%Y-%m-%d"),
  142. ("2011", "%Y"),
  143. ("2011-01", "%Y-%m"),
  144. ("30-12-2011", "%d-%m-%Y"),
  145. ("2011-12-30 00:00:00", "%Y-%m-%d %H:%M:%S"),
  146. ("2011-12-30T00:00:00", "%Y-%m-%dT%H:%M:%S"),
  147. ("2011-12-30T00:00:00UTC", "%Y-%m-%dT%H:%M:%S%Z"),
  148. ("2011-12-30T00:00:00Z", "%Y-%m-%dT%H:%M:%S%z"),
  149. ("2011-12-30T00:00:00+9", "%Y-%m-%dT%H:%M:%S%z"),
  150. ("2011-12-30T00:00:00+09", "%Y-%m-%dT%H:%M:%S%z"),
  151. ("2011-12-30T00:00:00+090", None),
  152. ("2011-12-30T00:00:00+0900", "%Y-%m-%dT%H:%M:%S%z"),
  153. ("2011-12-30T00:00:00-0900", "%Y-%m-%dT%H:%M:%S%z"),
  154. ("2011-12-30T00:00:00+09:00", "%Y-%m-%dT%H:%M:%S%z"),
  155. ("2011-12-30T00:00:00+09:000", None),
  156. ("2011-12-30T00:00:00+9:0", "%Y-%m-%dT%H:%M:%S%z"),
  157. ("2011-12-30T00:00:00+09:", None),
  158. ("2011-12-30T00:00:00.000000UTC", "%Y-%m-%dT%H:%M:%S.%f%Z"),
  159. ("2011-12-30T00:00:00.000000Z", "%Y-%m-%dT%H:%M:%S.%f%z"),
  160. ("2011-12-30T00:00:00.000000+9", "%Y-%m-%dT%H:%M:%S.%f%z"),
  161. ("2011-12-30T00:00:00.000000+09", "%Y-%m-%dT%H:%M:%S.%f%z"),
  162. ("2011-12-30T00:00:00.000000+090", None),
  163. ("2011-12-30T00:00:00.000000+0900", "%Y-%m-%dT%H:%M:%S.%f%z"),
  164. ("2011-12-30T00:00:00.000000-0900", "%Y-%m-%dT%H:%M:%S.%f%z"),
  165. ("2011-12-30T00:00:00.000000+09:00", "%Y-%m-%dT%H:%M:%S.%f%z"),
  166. ("2011-12-30T00:00:00.000000+09:000", None),
  167. ("2011-12-30T00:00:00.000000+9:0", "%Y-%m-%dT%H:%M:%S.%f%z"),
  168. ("2011-12-30T00:00:00.000000+09:", None),
  169. ("2011-12-30 00:00:00.000000", "%Y-%m-%d %H:%M:%S.%f"),
  170. ("Tue 24 Aug 2021 01:30:48", "%a %d %b %Y %H:%M:%S"),
  171. ("Tuesday 24 Aug 2021 01:30:48", "%A %d %b %Y %H:%M:%S"),
  172. ("Tue 24 Aug 2021 01:30:48 AM", "%a %d %b %Y %I:%M:%S %p"),
  173. ("Tuesday 24 Aug 2021 01:30:48 AM", "%A %d %b %Y %I:%M:%S %p"),
  174. ("27.03.2003 14:55:00.000", "%d.%m.%Y %H:%M:%S.%f"), # GH50317
  175. ],
  176. )
  177. def test_guess_datetime_format_with_parseable_formats(string, fmt):
  178. with tm.maybe_produces_warning(
  179. UserWarning, fmt is not None and re.search(r"%d.*%m", fmt)
  180. ):
  181. result = parsing.guess_datetime_format(string)
  182. assert result == fmt
  183. @pytest.mark.parametrize("dayfirst,expected", [(True, "%d/%m/%Y"), (False, "%m/%d/%Y")])
  184. def test_guess_datetime_format_with_dayfirst(dayfirst, expected):
  185. ambiguous_string = "01/01/2011"
  186. result = parsing.guess_datetime_format(ambiguous_string, dayfirst=dayfirst)
  187. assert result == expected
  188. @td.skip_if_not_us_locale
  189. @pytest.mark.parametrize(
  190. "string,fmt",
  191. [
  192. ("30/Dec/2011", "%d/%b/%Y"),
  193. ("30/December/2011", "%d/%B/%Y"),
  194. ("30/Dec/2011 00:00:00", "%d/%b/%Y %H:%M:%S"),
  195. ],
  196. )
  197. def test_guess_datetime_format_with_locale_specific_formats(string, fmt):
  198. result = parsing.guess_datetime_format(string)
  199. assert result == fmt
  200. @pytest.mark.parametrize(
  201. "invalid_dt",
  202. [
  203. "01/2013",
  204. "12:00:00",
  205. "1/1/1/1",
  206. "this_is_not_a_datetime",
  207. "51a",
  208. "13/2019",
  209. "202001", # YYYYMM isn't ISO8601
  210. "2020/01", # YYYY/MM isn't ISO8601 either
  211. "87156549591102612381000001219H5",
  212. ],
  213. )
  214. def test_guess_datetime_format_invalid_inputs(invalid_dt):
  215. # A datetime string must include a year, month and a day for it to be
  216. # guessable, in addition to being a string that looks like a datetime.
  217. assert parsing.guess_datetime_format(invalid_dt) is None
  218. @pytest.mark.parametrize("invalid_type_dt", [9, datetime(2011, 1, 1)])
  219. def test_guess_datetime_format_wrong_type_inputs(invalid_type_dt):
  220. # A datetime string must include a year, month and a day for it to be
  221. # guessable, in addition to being a string that looks like a datetime.
  222. with pytest.raises(
  223. TypeError,
  224. match=r"^Argument 'dt_str' has incorrect type \(expected str, got .*\)$",
  225. ):
  226. parsing.guess_datetime_format(invalid_type_dt)
  227. @pytest.mark.parametrize(
  228. "string,fmt,dayfirst,warning",
  229. [
  230. ("2011-1-1", "%Y-%m-%d", False, None),
  231. ("2011-1-1", "%Y-%d-%m", True, None),
  232. ("1/1/2011", "%m/%d/%Y", False, None),
  233. ("1/1/2011", "%d/%m/%Y", True, None),
  234. ("30-1-2011", "%d-%m-%Y", False, UserWarning),
  235. ("30-1-2011", "%d-%m-%Y", True, None),
  236. ("2011-1-1 0:0:0", "%Y-%m-%d %H:%M:%S", False, None),
  237. ("2011-1-1 0:0:0", "%Y-%d-%m %H:%M:%S", True, None),
  238. ("2011-1-3T00:00:0", "%Y-%m-%dT%H:%M:%S", False, None),
  239. ("2011-1-3T00:00:0", "%Y-%d-%mT%H:%M:%S", True, None),
  240. ("2011-1-1 00:00:00", "%Y-%m-%d %H:%M:%S", False, None),
  241. ("2011-1-1 00:00:00", "%Y-%d-%m %H:%M:%S", True, None),
  242. ],
  243. )
  244. def test_guess_datetime_format_no_padding(string, fmt, dayfirst, warning):
  245. # see gh-11142
  246. msg = (
  247. rf"Parsing dates in {fmt} format when dayfirst=False \(the default\) "
  248. "was specified. "
  249. "Pass `dayfirst=True` or specify a format to silence this warning."
  250. )
  251. with tm.assert_produces_warning(warning, match=msg):
  252. result = parsing.guess_datetime_format(string, dayfirst=dayfirst)
  253. assert result == fmt
  254. def test_try_parse_dates():
  255. arr = np.array(["5/1/2000", "6/1/2000", "7/1/2000"], dtype=object)
  256. result = parsing.try_parse_dates(arr, parser=lambda x: du_parse(x, dayfirst=True))
  257. expected = np.array([du_parse(d, dayfirst=True) for d in arr])
  258. tm.assert_numpy_array_equal(result, expected)
  259. def test_parse_datetime_string_with_reso_check_instance_type_raise_exception():
  260. # issue 20684
  261. msg = "Argument 'date_string' has incorrect type (expected str, got tuple)"
  262. with pytest.raises(TypeError, match=re.escape(msg)):
  263. parse_datetime_string_with_reso((1, 2, 3))
  264. result = parse_datetime_string_with_reso("2019")
  265. expected = (datetime(2019, 1, 1), "year")
  266. assert result == expected
  267. @pytest.mark.parametrize(
  268. "fmt,expected",
  269. [
  270. ("%Y %m %d %H:%M:%S", True),
  271. ("%Y/%m/%d %H:%M:%S", True),
  272. (r"%Y\%m\%d %H:%M:%S", True),
  273. ("%Y-%m-%d %H:%M:%S", True),
  274. ("%Y.%m.%d %H:%M:%S", True),
  275. ("%Y%m%d %H:%M:%S", True),
  276. ("%Y-%m-%dT%H:%M:%S", True),
  277. ("%Y-%m-%dT%H:%M:%S%z", True),
  278. ("%Y-%m-%dT%H:%M:%S%Z", False),
  279. ("%Y-%m-%dT%H:%M:%S.%f", True),
  280. ("%Y-%m-%dT%H:%M:%S.%f%z", True),
  281. ("%Y-%m-%dT%H:%M:%S.%f%Z", False),
  282. ("%Y%m%d", True),
  283. ("%Y%m", False),
  284. ("%Y", True),
  285. ("%Y-%m-%d", True),
  286. ("%Y-%m", True),
  287. ],
  288. )
  289. def test_is_iso_format(fmt, expected):
  290. # see gh-41047
  291. result = strptime._test_format_is_iso(fmt)
  292. assert result == expected
  293. @pytest.mark.parametrize(
  294. "input",
  295. [
  296. "2018-01-01T00:00:00.123456789",
  297. "2018-01-01T00:00:00.123456",
  298. "2018-01-01T00:00:00.123",
  299. ],
  300. )
  301. def test_guess_datetime_format_f(input):
  302. # https://github.com/pandas-dev/pandas/issues/49043
  303. result = parsing.guess_datetime_format(input)
  304. expected = "%Y-%m-%dT%H:%M:%S.%f"
  305. assert result == expected