前言
Pydantic 支持 datatime 模块的日期和时间类型
datetime 日期时间类型
datetime字段可以是:
- datetime, 现有datetime对象
- int或float,假定为 Unix 时间,即自 1970 年 1 月 1 日以来的秒数(if >= -2e10 or <= 2e10))或毫秒 (if < -2e10or > 2e10)
- str, 以下格式有效:
YYYY-MM-DD[T]HH:MM[:SS[.ffffff]][Z or [±]HH[:]MM]]]
int或float作为字符串(假定为 Unix 时间)
使用示例
from datetime import datetime
from pydantic import BaseModel, validator
class Book(BaseModel):
id: int
name: str
create_time: datetime = None
@validator('create_time', pre=True, always=True)
def set_create_now(cls, v):
return v or datetime.now()
# 1.传datetime 对象
book1 = Book(id=1, name='python', create_time=datetime.now())
print(book1.json())
# 2.传字符串
book2 = Book(id=1, name='python', create_time="2022-02-21T11:23:10.707257")
print(book2.json())
# 3.Unix 时间戳
book2 = Book(id=1, name='python', create_time=1645506606260)
print(book2.json())
data 日期类型
date字段可以是:
- date, 现有date对象
- int或float,见datetime Unix 时间
- str, 以下格式有效:YYYY-MM-DD int或float,见datetime Unix 时间
from datetime import datetime, date
from pydantic import BaseModel, validator
class Book(BaseModel):
id: int
name: str
create_time: date = None
@validator('create_time', pre=True, always=True)
def set_create_now(cls, v):
return v or date.today()
# 1.传date 对象
book1 = Book(id=1, name='python', create_time=date.today())
print(book1.json())
# 2.传字符串
book2 = Book(id=1, name='python', create_time="2022-02-21")
print(book2.json())
# 3.Unix 时间戳
book2 = Book(id=1, name='python', create_time=1645506606260)
print(book2.json())
time 字段
time字段可以是:
- time, 现有time对象
- str, 以下格式有效:HH:MM[:SS[.ffffff]][Z or [±]HH[:]MM]]]
from datetime import datetime, date, time, timedelta
from pydantic import BaseModel, validator
class Book(BaseModel):
id: int
name: str
create_time: time
# 1.传time 对象
book1 = Book(id=1, name='python', create_time=time(13, 26, 16))
print(book1.json()) # {"id": 1, "name": "python", "create_time": "13:26:16"}
# 2.传字符串
book2 = Book(id=1, name='python', create_time="13:26:16")
print(book2.json()) # {"id": 1, "name": "python", "create_time": "13:26:16"}
timedelta字段
datetime.timedelta对象代表两个时间之间的时间差,两个date或datetime对象相减就可以返回一个timedelta对象。
timedelta字段可以是:
- timedelta, 现有timedelta对象
- int或float, 假定为秒
- str, 以下格式有效:[-][DD ][HH:MM]SS[.ffffff] 和 [±]P[DD]DT[HH]H[MM]M[SS]S(时间增量的 ISO 8601 格式)
from datetime import date, datetime, time, timedelta
from pydantic import BaseModel
class Model(BaseModel):
d: date = None
dt: datetime = None
t: time = None
td: timedelta = None
m = Model(
d=1966280412345.6789,
dt='2032-04-23T10:20:30.400+02:30',
t=time(4, 8, 16),
td='P3DT12H30M5S',
)
print(m.dict())
"""
{
'd': datetime.date(2032, 4, 22),
'dt': datetime.datetime(2032, 4, 23, 10, 20, 30, 400000,
tzinfo=datetime.timezone(datetime.timedelta(seconds=9000))),
't': datetime.time(4, 8, 16),
'td': datetime.timedelta(days=3, seconds=45005),
}
"""