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

Converting date objects #51

Open
mudassarzahid opened this issue Nov 23, 2024 · 4 comments
Open

Converting date objects #51

mudassarzahid opened this issue Nov 23, 2024 · 4 comments

Comments

@mudassarzahid
Copy link

Is there a way to support datetime / date to Date conversions? Currently, they are converted to string.

  • Python input:
from datetime import date

class MyModel(BaseModel):
    start_date: date
  • TypeScript output:
export interface MyModel {
  start_date: string;  // should be Date
}
@phillipdupuis
Copy link
Owner

Hi @mudassarzahid, it turns out this actually is possible. I didn't expect that!

All you need to do is add {"tsType": "Date"} to the json_schema_extra for date/datetime fields.

Example:

import datetime
from pydantic import BaseModel, Field

class MyModel(BaseModel):
    a: datetime.date = Field(json_schema_extra={"tsType": "Date"})
    b: datetime.datetime = Field(json_schema_extra={"tsType": "Date"})

yields

export interface MyModel {
  a: Date;
  b: Date;
}

@phillipdupuis
Copy link
Owner

And if you want to automatically make this change EVERYWHERE in a project, I'd recommend using typing.Annotated like so:

import datetime
from typing import Annotated
from pydantic import BaseModel, Field

Date = Annotated[datetime.date, Field(json_schema_extra={"tsType": "Date"})]
DateTime = Annotated[datetime.datetime, Field(json_schema_extra={"tsType": "Date"})]

class MyModel(BaseModel):
    a: Date
    b: DateTime

Use the annotated Date and DateTime types in place of datetime.date/datetime.datetime and it will all just work.

You could probably also do this by modifying the pydantic schema generator, but those APIs always seem to be in flux so in my eyes it's not worth the effort.

@phillipdupuis
Copy link
Owner

Does this work as a solution for you?

I don't think I'll make this into a standard thing, since string is technically the correct type (in terms of JSON serialization). But it's good to know that it's possible.

@mudassarzahid
Copy link
Author

@phillipdupuis That's perfect, thank you!

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

No branches or pull requests

2 participants