Skip to content

Commit

Permalink
Add is_iso8601() function
Browse files Browse the repository at this point in the history
  • Loading branch information
singingwolfboy authored and micktwomey committed Sep 28, 2022
1 parent 406db6f commit 21f5368
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 2 deletions.
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ Python 3 versions < 3.6 are untested but should work.
Changes
=======

unreleased
----------
* Add `is_iso8601` function for validating that a string matches an ISO 8601 format

1.0.2
-----

Expand Down
2 changes: 2 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ To install simply use pip::
API
===

.. autofunction:: iso8601.is_iso8601

.. autofunction:: iso8601.parse_date

.. autoexception:: iso8601.ParseError
Expand Down
4 changes: 2 additions & 2 deletions iso8601/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .iso8601 import UTC, FixedOffset, ParseError, parse_date
from .iso8601 import UTC, FixedOffset, ParseError, is_iso8601, parse_date

__all__ = ["parse_date", "ParseError", "UTC", "FixedOffset"]
__all__ = ["parse_date", "is_iso8601" "ParseError", "UTC", "FixedOffset"]
13 changes: 13 additions & 0 deletions iso8601/iso8601.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,16 @@ def parse_date(
)
except Exception as e:
raise ParseError(e)


def is_iso8601(datestring: str) -> bool:
"""Check if a string matches an ISO 8601 format.
:param datestring: The string to check for validity
:returns: True if the string matches an ISO 8601 format, False otherwise
"""
try:
m = ISO8601_REGEX.match(datestring)
return bool(m)
except Exception:
return False
2 changes: 2 additions & 0 deletions iso8601/test_iso8601.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def test_parse_utc_different_default() -> None:
],
)
def test_parse_invalid_date(invalid_date: str, error_string: str) -> None:
assert iso8601.is_iso8601(invalid_date) is False
with pytest.raises(iso8601.ParseError) as exc:
iso8601.parse_date(invalid_date)
assert exc.errisinstance(iso8601.ParseError)
Expand Down Expand Up @@ -243,6 +244,7 @@ def test_parse_invalid_date(invalid_date: str, error_string: str) -> None:
def test_parse_valid_date(
valid_date: str, expected_datetime: datetime.datetime, isoformat: str
) -> None:
assert iso8601.is_iso8601(valid_date) is True
parsed = iso8601.parse_date(valid_date)
assert parsed.year == expected_datetime.year
assert parsed.month == expected_datetime.month
Expand Down

0 comments on commit 21f5368

Please sign in to comment.