SQLAlchemy Core中如何将datetime格式数据转换为dd.mm.YYYY格式输出
SQLAlchemy Core查询日期转DD.MM.YYYY格式实现方法
有三种常用实现方式,可根据你的技术栈选择:
方案1:SQL查询阶段直接转换(性能最优)
利用数据库原生的日期格式化函数,在查询时直接返回目标格式的字符串,不需要额外处理逻辑。
需要根据你使用的数据库类型选择对应函数,修改查询语句中的日期字段即可:
- MySQL:用
DATE_FORMAT函数 - PostgreSQL:用
TO_CHAR函数 - SQLite:用
STRFTIME函数
示例(以MySQL为例):
首先导入SQLAlchemy的func工具:
from sqlalchemy import func
修改你的select语句中的日期字段:
s = select([ report.c.id, # 格式化created_at字段,输出格式为日.月.年 func.date_format(report.c.created_at, '%d.%m.%Y').label('created_at'), report.c.filename, report.c.filepath, report.c.period_type, report.c.reporting_period, # 其他日期字段同理修改,比如sign_at func.date_format(report.c.sign_at, '%d.%m.%Y').label('sign_at'), report.c.is_deleted, author, organization, category ]).select_from(j).where(report.c.is_deleted == False).order_by(report.c.id)
其他数据库对应写法参考:
- PostgreSQL:
func.to_char(report.c.created_at, 'DD.MM.YYYY').label('created_at')- SQLite:
func.strftime('%d.%m.%Y', report.c.created_at).label('created_at')
方案2:Python结果遍历转换(无数据库依赖)
如果不想修改查询语句,或者需要兼容多种数据库,可在拿到查询结果后遍历转换日期字段:
# 执行查询拿到映射格式的结果 result = db_connection.execute(s).mappings().all() # 遍历处理每个条目 for item in result: # 处理created_at if item["created_at"]: item["created_at"] = item["created_at"].strftime("%d.%m.%Y") # 处理sign_at等其他日期字段 if item["sign_at"]: item["sign_at"] = item["sign_at"].strftime("%d.%m.%Y")
方案3:序列化框架自动转换(适合有DTO校验的场景)
如果你用了Pydantic这类序列化框架返回给前端,可直接在模型中配置日期格式的全局转换规则,不需要手动处理每一条数据:
from pydantic import BaseModel from datetime import date class ReportResp(BaseModel): id: int created_at: str filename: str # 其他字段按需补充 class Config: json_encoders = { # 全局指定date类型的序列化格式 date: lambda d: d.strftime("%d.%m.%Y") } # 直接将查询结果传入模型即可自动转换 resp_list = [ReportResp(**item) for item in result]
内容的提问来源于stack exchange,提问作者Nikolay Vatan
相关产品推荐
相关产品推荐

