koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.44k stars 281 forks source link

Support NaiveDateTime #1996

Open pmbrull opened 3 weeks ago

pmbrull commented 3 weeks ago

Is your feature request related to a problem? Please describe. Add support to choose between AwareDateTime, NaiveDateTime or generic datetime.

Describe the solution you'd like A CLI option to choose between the both.

Describe alternatives you've considered Updating the generated models

Additional context Migrating to pydantic v2 has proven to be very time consuming. Typing becomes more strict, which is a good thing, but going the extra mile as to update the full codebase to ensure all datetime objects are using a timezone is too demanding when interact with other tools such as SQLAlchemy, etc.

Pydantic V2 supports:

Being able to use the later would make things much easier.

Thanks

devmonkey22 commented 1 week ago

I know this was mentioned in the original PR #1735 and also brought up in #1944 (but closed), I have a similar need. I can't modify the source system to properly generate timezone strict output (all datetimes are already generated in UTC, but don't serialize to JSON that keeps the AwareDatetime happy). Datetimes that are in ISO 8601 format like "2024-05-29T18:00:29.526990Z" are fine with AwareDatetime at least. But I can't guarantee.

As a workaround to consume the JSON, while I dislike it, I currently have a script that calls datamodel_code_generator.codegen.generate programmatically instead of via direct CLI, so I can monkeypatch the datamodel_code_generator.model.pydantic_v2.types.IMPORT_AWARE_DATETIME value before generating like:

    # Patch to use naive datetime instead of default AwareDatetime
    from datamodel_code_generator.imports import Import
    from datamodel_code_generator.model.pydantic_v2 import types as pydantic_v2_types
    pydantic_v2_types.IMPORT_AWARE_DATETIME = Import.from_full_path('pydantic.NaiveDatetime')

    codegen.generate(
        ...
    )

Then my outputs properly use NaiveDatetime like I want.

Similarly, if I wanted to use the original standard datetime.datetime, just use Import.from_full_path('datetime.datetime')

Alternatively, I could have patched/overridden the pydantic_v2.types.DataTypeManager class and its type_map_factory method, but that seemed more complicated to subclass and inject into the generate/parser.

Obviously long-term, it would be great to have an official way to customize.