diff --git a/docs/docs/parsing.md b/docs/docs/parsing.md index dd78fd45a..0a3c31a7e 100644 --- a/docs/docs/parsing.md +++ b/docs/docs/parsing.md @@ -82,6 +82,8 @@ ParserError: Unable to parse string [31-01-01] ### Time When passing only time information the date will default to today. +To give just the hour, include the `T` prefix, as in `T13`. A bare `13` raises +`ParserError` in strict mode. | String | Output | | --------------------------------- | ------------------------------------------ | diff --git a/src/pendulum/parsing/iso8601.py b/src/pendulum/parsing/iso8601.py index c65d249e5..452ca7a95 100644 --- a/src/pendulum/parsing/iso8601.py +++ b/src/pendulum/parsing/iso8601.py @@ -199,6 +199,8 @@ def parse_iso8601( raise ParserError(f"Invalid date string: {text}") if not is_date: + if not m.group("minute") and m.group("timesep") != "T": + raise ParserError("Invalid ISO 8601 time part") is_time = True # Grabbing hh:mm:ss diff --git a/tests/test_parsing.py b/tests/test_parsing.py index 34673c40a..b9cfd22d3 100644 --- a/tests/test_parsing.py +++ b/tests/test_parsing.py @@ -1,7 +1,10 @@ from __future__ import annotations +import pytest + import pendulum +from pendulum.parsing import ParserError from tests.conftest import assert_date from tests.conftest import assert_datetime from tests.conftest import assert_duration @@ -37,6 +40,27 @@ def test_parse() -> None: assert dt.offset == 0 +@pytest.mark.parametrize("text", ["13", "13Z", "13+02:00"]) +def test_parse_rejects_bare_hour(text: str) -> None: + with pytest.raises(ParserError): + pendulum.parse(text) + + +def test_parse_prefixed_hour() -> None: + dt = pendulum.parse("T13", now=pendulum.datetime(2015, 11, 12)) + + assert isinstance(dt, pendulum.DateTime) + assert_datetime(dt, 2015, 11, 12, 13, 0, 0) + + +def test_parse_bare_hour_non_strict() -> None: + with pendulum.travel_to(pendulum.datetime(2015, 11, 12), freeze=True): + dt = pendulum.parse("13", strict=False) + + assert isinstance(dt, pendulum.DateTime) + assert_datetime(dt, 2015, 11, 13, 0, 0, 0) + + def test_parse_with_timezone() -> None: text = "2016-10-16T12:34:56.123456"