使用
type decorator处理与自定义格式之间的转换.定义列时,请使用此类型而不是String.
class MyTime(TypeDecorator):
impl = String
def __init__(self, length=None, format='%H:%M:%S', **kwargs)
super().__init__(length, **kwargs)
self.format = format
def process_literal_param(self, value, dialect):
# allow passing string or time to column
if isinstance(value, basestring): # use str instead on py3
value = datetime.strptime(value, self.format).time()
# convert python time to sql string
return value.strftime(self.format) if value is not None else None
process_bind_param = process_literal_param
def process_result_value(self, value, dialect):
# convert sql string to python time
return datetime.strptime(value, self.format).time() if value is not None else None
# in your model
class MyModel(Base):
time = Column(MyTime(length=7))