Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify type conversio in XsdDate/XsdDateTime deserializers #139

Merged
merged 1 commit into from
Oct 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions serializable/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def json_deserialize(cls, o: Any) -> Any:

# endregion json specific

# endregion xml specific
# region xml specific

@classmethod
def xml_normalize(cls, o: Any, *,
Expand Down Expand Up @@ -155,21 +155,22 @@ def serialize(cls, o: Any) -> str:
@classmethod
def deserialize(cls, o: Any) -> date:
try:
if str(o).startswith('-'):
v = str(o)
if v.startswith('-'):
# Remove any leading hyphen
o = str(o)[1:]
v = v[1:]

if str(o).endswith('Z'):
o = str(o)[:-1]
if v.endswith('Z'):
v = v[:-1]
_logger.warning(
'Potential data loss will occur: dates with timezones not supported in Python',
stacklevel=2)
if '+' in str(o):
o = str(o)[:str(o).index('+')]
if '+' in v:
v = v[:v.index('+')]
_logger.warning(
'Potential data loss will occur: dates with timezones not supported in Python',
stacklevel=2)
return date.fromisoformat(str(o))
return date.fromisoformat(v)
except ValueError:
raise ValueError(f'Date string supplied ({o}) is not a supported ISO Format')

Expand Down Expand Up @@ -197,16 +198,18 @@ def serialize(cls, o: Any) -> str:
@classmethod
def deserialize(cls, o: Any) -> datetime:
try:
if str(o).startswith('-'):
v = str(o)
if v.startswith('-'):
# Remove any leading hyphen
o = str(o)[1:]
v = v[1:]

# Ensure any milliseconds are 6 digits
o = re_sub(r'\.(\d{1,6})', lambda v: f'.{int(v.group()[1:]):06}', str(o))
# Background: py<3.11 supports six or less digits for milliseconds
v = re_sub(r'\.(\d{1,6})', lambda m: f'.{int(m.group()[1:]):06}', v)

if str(o).endswith('Z'):
if v.endswith('Z'):
# Replace ZULU time with 00:00 offset
o = f'{str(o)[:-1]}+00:00'
return datetime.fromisoformat(str(o))
v = f'{v[:-1]}+00:00'
return datetime.fromisoformat(v)
except ValueError:
raise ValueError(f'Date-Time string supplied ({o}) is not a supported ISO Format')
Loading