Skip to content

Use AwareDateTime when generating field from DateTime(timezone=True) (#407) - #741

Open
DYNOSuprovo wants to merge 1 commit into
marshmallow-code:devfrom
DYNOSuprovo:fix/datetime-timezone-aware-407
Open

DYNOSuprovo wants to merge 1 commit into
marshmallow-code:devfrom
DYNOSuprovo:fix/datetime-timezone-aware-407

Conversation

@DYNOSuprovo

Copy link
Copy Markdown

Closes #407.

Summary

When generating a marshmallow field for a SQLAlchemy column of type DateTime(timezone=True) (or dialect equivalents such as postgresql.TIMESTAMP(timezone=True), mysql.DATETIME(timezone=True), and mssql.DATETIMEOFFSET), ModelConverter currently generates a default fields.DateTime. This forces schemas to explicitly override auto-generated fields with fields.AwareDateTime.

Solution

  • Added _datetime_field_factory and registered sa.DateTime and mysql.DATETIME in ModelConverter.SQLA_TYPE_MAPPING.
  • If getattr(data_type, "timezone", False) is True (or if it is an instance of mssql.DATETIMEOFFSET), the factory returns fields.AwareDateTime.
  • Otherwise, it falls back to converter.type_mapping.get(dt.datetime, fields.DateTime), fully preserving existing behavior and custom schema TYPE_MAPPING overrides for naive datetimes.
  • Added unit tests in tests/test_conversion.py for standard and dialect types (sa.DateTime, postgresql.TIMESTAMP, mysql.DATETIME, mssql.DATETIMEOFFSET, sa.TIMESTAMP) and in tests/test_sqlalchemy_schema.py for SQLAlchemyAutoSchema.

…arshmallow-code#407)

Signed-off-by: DYNOSuprovo <DYNOSuprovo@users.noreply.github.com>
@lafrech

lafrech commented Oct 3, 2026

Copy link
Copy Markdown
Member

Looks good.

Please see our AI policy if you haven't already.

Also wondering if we should use a NaiveDateTime in other cases. Let's keep the conversation in #407.

@DYNOSuprovo

Copy link
Copy Markdown
Author

Thank you @lafrech! I will follow up in #407 regarding the NaiveDateTime discussion.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use AwareDateTime when generating field from DateTime(timezone=True)

2 participants