【问题标题】:make Sqllite preserve datetime object使 Sqlite 保留日期时间对象
【发布时间】:2022-01-13 00:35:20
【问题描述】:

我正在尝试编写一个 pytest 夹具,它返回一些 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

如何保留 datetime 对象?

【问题讨论】:

标签: sqlite sqlalchemy


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    相关资源
    最近更新 更多