使用带有mysql unix时间戳的sqlalchemy定义表
问题内容:
背景技术,有几种方法可以在MySQ中存储日期。
- 作为字符串,例如“ 09/09/2009”。
- 作为使用函数UNIX_TIMESTAMP()的整数,据说这是传统的unix时间表示形式(您知道自历元正负秒数以来的秒数)。
- 作为MySQL TIMESTAMP,特定于mysql的数据类型与unix时间戳不同。
- 作为MySQL Date字段,是另一个MySQL特定的数据类型。
请勿将案例2与案例3(或案例4)混淆。我有一个带有整数日期字段的现有表(情况2),如何在sqlalchemy中定义它,而不必访问mysql的“
FROM_UNIXTIME”函数?
作为记录,仅使用sqlalchemy.types.DateTime并希望它在检测到整数列时做正确的事情不起作用,它适用于时间戳记字段和日期字段。
问题答案:
我认为您显示的类型装饰器有几个问题。
impl
应该sqlalchemy.types.Integer
代替DateTime
。- 装饰器应允许可空列。
这就是我的想法:
import datetime, time
from sqlalchemy.types import TypeDecorator, DateTime, Integer
class IntegerDateTime(TypeDecorator):
"""a type that decorates DateTime, converts to unix time on
the way in and to datetime.datetime objects on the way out."""
impl = Integer # In schema, you want these datetimes to
# be stored as integers.
def process_bind_param(self, value, _):
"""Assumes a datetime.datetime"""
if value is None:
return None # support nullability
elif isinstance(value, datetime.datetime):
return int(time.mktime(value.timetuple()))
raise ValueError("Can operate only on datetime values. "
"Offending value type: {0}".format(type(value).__name__))
def process_result_value(self, value, _):
if value is not None: # support nullability
return datetime.datetime.fromtimestamp(float(value))