让 Sqlite 保留日期时间对象

make Sqllite preserve datetime object

我正在尝试编写一个 pytest 装置,returns 一些 List[sa.engine.row.LegacyRow] 类型的测试数据。

问题是 sqllite 将 datetime 对象转换为 str。

import sqlalchemy as sa
from datetime import datetime

# test data
data = {'id': '1',
        'date': datetime(2019, 12, 9, 14, 11, 2, 442076)}

sql = "SELECT " + ", ".join([f":{col} as {col}" for col in data]) # SELECT :col1 as col1, :col2 as col2

engine = sa.create_engine("sqlite:///:memory:")

with engine.begin() as conn:
    row = conn.execute(sa.text(sql), data).fetchall()
    print(row)
    print(type(row[0][1]))  # str

如何保留日期时间对象?

您可以使用 TextClause.columns 方法指定返回列的类型。

比如这段代码

with engine.begin() as conn:
    q = sa.text("""SELECT id, date FROM test WHERE id = :id AND date = :date""")
    q = q.columns(date=sa.DateTime)
    res = conn.execute(q, data)
    for row in res:
        for col in row:
            print(type(col), col)

产生这个输出:

<class 'int'> 1
<class 'datetime.datetime'> 2019-12-09 14:11:02.442076