Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify timezone in pydantic datetime field [Python]

I have a model where i have datetime type fields defined as shown:

class DamBaseModel(BaseModel):

    class Config:
        allow_population_by_field_name = True
        use_enum_values = True
        arbitrary_types_allowed = True
        json_encoders = {
            ObjectId: str,
            datetime: lambda d: d.isoformat
        }

The defined Model is as follows:

class Message(DamBaseModel):
    created_datetime: datetime = Field(default_factory=datetime.now)

The data that gets inserted into MongoDb is :

{ "created_datetime" : ISODate("2022-08-22T12:02:59.546Z") }

But the problem iam currently facing is that the data is received at the client level in this format :

{ "created_datetime": "Mon, 22 Aug 2022 12:02:59 GMT" }

Iam just fetching the data from the db and projecting it directly without any formatting. Any help as to how to specify local timezone when projecting the data ??

like image 502
SrTan Avatar asked Aug 28 '26 12:08

SrTan


1 Answers

Timezone aware timestamps are now supported in Pydantic V2:

from pydantic import AwareDatetime, TypeAdapter


dt = AwareDatetime
ta = TypeAdapter(dt)

# validate UTC timestamp
ta.validate_python("2022-08-22T12:02:59.546Z")

# Validate timestamp with timezone
ta.validate_python("2022-08-22T12:02:59.546+00:00")
like image 172
Yaakov Bressler Avatar answered Aug 31 '26 03:08

Yaakov Bressler