前言
使用datetime 日期类型时,想格式化成自定义的"%Y-%m-%d %H:%M:%S"
格式
datetime 类型
from pydantic import BaseModel
from datetime import datetime
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
class UserInfo(BaseModel):
id: int
name: str
create_time: datetime=datetime.now()
user = UserInfo(**{"id": 1, "name": "yoyo"})
print(user.json())
转json格式,输出结果
{"id": 1, "name": "yoyo", "create_time": "2023-10-10T16:47:27.023813"}
'create_time'日期时间格式,我期望得到的格式是2023-10-10 16:47:27
json_encoders 格式化 datetime 类型
json_encoders 可以格式指定的类型
from pydantic import BaseModel
from datetime import datetime
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
class UserInfo(BaseModel):
id: int
name: str
create_time: datetime=datetime.now()
class Config:
json_encoders = {
datetime: lambda v: v.strftime("%Y-%m-%d %H:%M:%S")
}
user = UserInfo(**{"id": 1, "name": "yoyo"})
print(user.json())
运行结果:
{"id": 1, "name": "yoyo", "create_time": "2023-10-10 16:48:47"}
标签:encoders,name,17,create,datetime,json,id
From: https://www.cnblogs.com/yoyoketang/p/17755131.html