Skip to content

Commit

Permalink
Preserve timezone information when validating Pendulum DateTimes
Browse files Browse the repository at this point in the history
Fixes #188
  • Loading branch information
chrisguidry committed Jun 13, 2024
1 parent 5edf337 commit ce8d401
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ _build/
/.ghtopdep_cache/
/worktrees/
.ruff_cache/
.python-version
11 changes: 1 addition & 10 deletions pydantic_extra_types/pendulum_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,7 @@ def _validate(cls, value: Any, handler: core_schema.ValidatorFunctionWrapHandler
# probably the best way to have feature parity with
# https://docs.pydantic.dev/latest/api/standard_library_types/#datetimedatetime
value = handler(value)
return DateTime(
value.year,
value.month,
value.day,
value.hour,
value.minute,
value.second,
value.microsecond,
value.tzinfo,
)
return DateTime.instance(value)
except ValueError:
try:
value = parse(value, strict=cls.strict)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_pendulum_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,32 @@ def test_pendulum_dt_from_serialized(dt):
assert isinstance(model.dt, pendulum.DateTime)


@pytest.mark.parametrize(
'dt',
[
pendulum.now().to_iso8601_string(),
pendulum.now().to_w3c_string(),
],
)
def test_pendulum_dt_from_serialized_preserves_timezones(dt):
"""
Verifies that building an instance from serialized, well-formed strings decode
properly and preserves the timezone information across all of the Pendulum DateTime
properties. Regression test for pydantic/pydantic-extra-types#188.
"""
dt_actual = pendulum.parse(dt)
model = DtModel(dt=dt)
assert model.dt == dt_actual
assert type(model.dt) is DateTime
assert isinstance(model.dt, pendulum.DateTime)
assert model.dt.tzinfo is not None
assert model.dt.tzinfo.utcoffset(model.dt) == dt_actual.tzinfo.utcoffset(dt_actual)
assert model.dt.tz is not None
assert model.dt.tz.utcoffset(model.dt) == dt_actual.tz.utcoffset(dt_actual)
assert model.dt.timezone is not None
assert model.dt.timezone.utcoffset(model.dt) == dt_actual.timezone.utcoffset(dt_actual)


@pytest.mark.parametrize(
'dt',
[
Expand Down

0 comments on commit ce8d401

Please sign in to comment.