You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Peewee实现Postgres中hrreference字段的两种时间格式化查询?

使用Peewee实现Postgres时间字段的两种查询需求

针对你需要获取的两个结果列,以下是对应的Peewee实现方式:

1. 获取 hrreference::time(0)(截断毫秒的时间类型)

这个操作是将字段转换为不带毫秒的time类型,在Peewee中有两种实现方式:

方式一:使用类型转换函数

from peewee import SQL
from your_model_module import Document  # 替换为你的模型导入路径

# 查询并别名结果列
query = Document.select(
    Document.hrreference.cast(SQL('time(0)')).alias('truncated_time')
)

# 遍历结果
for record in query:
    print(record.truncated_time)

方式二:直接使用原生SQL表达式

如果更习惯原生SQL写法,也可以直接构造表达式:

query = Document.select(
    SQL('hrreference::time(0)').alias('truncated_time')
)

2. 获取 to_char(hrreference, 'HH24:MI:SS.US')(带微秒的格式化字符串)

Postgres的to_char函数可以通过Peewee的fn工具类直接调用,实现时间格式化:

from peewee import fn
from your_model_module import Document

# 调用to_char函数并别名结果列
query = Document.select(
    fn.to_char(Document.hrreference, 'HH24:MI:SS.US').alias('formatted_time')
)

# 遍历结果
for record in query:
    print(record.formatted_time)

同时获取两个列

如果需要一次性获取两个结果,只需将两个字段表达式同时加入select中:

from peewee import SQL, fn
from your_model_module import Document

query = Document.select(
    Document.hrreference.cast(SQL('time(0)')).alias('truncated_time'),
    fn.to_char(Document.hrreference, 'HH24:MI:SS.US').alias('formatted_time')
)

for record in query:
    print(f"截断毫秒的时间: {record.truncated_time}, 带微秒的格式化字符串: {record.formatted_time}")

注意事项

  • 确保你的Document模型中hrreference字段的类型与数据库实际类型匹配(如DateTimeField或TimestampField)。
  • 若使用Postgres扩展功能,需确保导入了playhouse.postgres_ext中的数据库连接类。

内容的提问来源于stack exchange,提问作者Elias Coutinho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:35:25