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

Preserve timezone information when validating Pendulum DateTimes #189

Merged
merged 1 commit into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
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
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
Loading