How to create timestamps automatically for MongoDB Schemas in python?

Viewed 1642

How can i create timestamps automatically in my schemas in python?

For example in Javascript you can do something like this

var thingSchema = new Schema({..}, { timestamps: true });

timestamps: true will create created_at and update_at field in my schema and it will also update updated_at field every time i change something in that document How can i achieve this in python

My python schema looks like this

class UserSchema(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    user_name: str = Field(...)
    user_email: EmailStr = Field(...)
    
    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}
1 Answers

I'm not sure what you mean with create timestamps automatically, but if you mean to add the timestamp at instantiation

import datetime
class UserSchema(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    user_name: str = Field(...)
    user_email: EmailStr = Field(...)
    timestamp: datetime.datetime = datetime.datetime.now()
    
    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

Here's the link to the official docs, which provides more extensive examples about the different dates and times supported.

https://pydantic-docs.helpmanual.io/usage/types/#datetime-types

Related