前言
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),
}
"""
