Skip to content

Commit

Permalink
Fixed ISO-format decoding problems
Browse files Browse the repository at this point in the history
  • Loading branch information
mmabey committed Apr 27, 2021
1 parent cad9d32 commit 379696f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
28 changes: 19 additions & 9 deletions fhirdatetime/__init__.py
Expand Up @@ -29,6 +29,7 @@
>>> FhirDateTime(2021) > FhirDateTime(2021, 3, 15)
False
"""
import re
from datetime import MAXYEAR, MINYEAR, date, datetime, timezone, tzinfo as tzinfo_
from operator import itemgetter
from typing import Optional, Union
Expand All @@ -43,10 +44,13 @@
)

__all__ = ["FhirDateTime", "__version__"]
__version__ = "0.1.0b6"
__version__ = "0.1.0b8"

DATE_FIELDS = ("year", "month", "day")
TIME_FIELDS = ("hour", "minute", "second", "microsecond")
_y_pat = re.compile(r"^(\d{4})$")
_ym_pat = re.compile(r"^(\d{4})-(\d{2})$")
_ymd_pat = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")

ComparableTypes = Union["FhirDateTime", datetime, date]

Expand Down Expand Up @@ -221,23 +225,29 @@ def isoformat(self, sep: str = "T", timespec: str = "auto") -> str:
@classmethod
def fromisoformat(cls, date_string: str):
"""Construct a FhirDateTime from the output of FhirDateTime.isoformat()."""
# Check for shorter formats first
for pat in (_y_pat, _ym_pat, _ymd_pat):
m = re.match(pat, date_string)
if m:
return FhirDateTime(*[int(p) for p in m.groups()])

try:
return super().fromisoformat(date_string)
except (ValueError, IndexError):
pass

for fmt in ("%Y-%m-%dT%H:%M:%S.%f%Z", "%Y", "%Y-%m", "%Y-%m-%d"):
for fmt in ("%Y-%m-%dT%H:%M:%S.%fZ", "%Y-%m-%dT%H:%M:%SZ"):
# These formats need to have the UTC timezone inserted after creation
try:
return cls.strptime(date_string, fmt).replace(tzinfo=timezone.utc)
except ValueError:
pass

for fmt in ("%Y-%m-%dT%H:%M:%S.%f%Z", "%Y-%m-%dT%H:%M:%S%Z"):
try:
return cls.strptime(date_string, fmt)
except ValueError as err:
last_err = err
continue
try:
return cls.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ").replace(
tzinfo=timezone.utc
)
except ValueError:
pass
raise last_err

@staticmethod
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Expand Up @@ -6,7 +6,7 @@ combine_as_imports = true

[tool.poetry]
name = "fhirdatetime"
version = "0.1.0b6"
version = "0.1.0b8"
description = "A datetime-compatible class for FHIR date/datetime values."
authors = ["Mike Mabey <mmabey@ieee.org>"]
homepage = "https://github.com/mmabey/fhirdatetime"
Expand Down
6 changes: 5 additions & 1 deletion tests/test_fhirdatetime.py
Expand Up @@ -16,7 +16,7 @@

def test_version():
"""Check library version is what it should be."""
ver = "0.1.0b6"
ver = "0.1.0b8"
assert __version__ == ver
with open("pyproject.toml") as proj:
for line in proj:
Expand Down Expand Up @@ -249,3 +249,7 @@ def test_other_methods():
2020, 5, 4, 13, 42, 54, 295815, timezone(timedelta(hours=3))
)
assert dt.timestamp() == 1588588974.295815

assert str(FhirDateTime("2020")) == "2020"
assert str(FhirDateTime("2020-05")) == "2020-05"
assert str(FhirDateTime("2020-05-04")) == "2020-05-04"

0 comments on commit 379696f

Please sign in to comment.