【问题标题】:how to change datetime to string in sqlalchemy query? [duplicate]如何在 sqlalchemy 查询中将日期时间更改为字符串? [复制]
【发布时间】:2017-02-18 23:35:23
【问题描述】:

这是我的代码,查询 Notification.create_time

result = session.query(
        Notification.content, cls.is_read,
        Notification.create_time).join(
        cls, Notification.id == cls.notification).filter(
            and_(cls.user == user_id)).order_by(
                Notification.create_time.desc()).all()

在其他地方需要json.dumps查询结果到前端,datetime格式不能json.dumps,所以我想这样做:

session.query(Notification.create_time.strftime('%Y-%m-%d %H:%M'))

那么,如何在 sqlalchemy 查询中将日期时间更改为字符串?

【问题讨论】:

标签: python sqlalchemy


【解决方案1】:

可以使用func.to_char()(在postgres中,不确定mysql)将日期时间转换为字符串,例如:

from sqlalchemy.sql import func
session.query(func.to_char(Notification.create_time, '%Y-%m-%d %H:%M'))

但更好的方法是设置您的 json 序列化程序来处理日期时间之类的事情,as is described in this answer

【讨论】:

  • 你太棒了。谢谢你变化很大~~~~~~~~
  • 这种格式在 Postgres 中对我有用 'Dy, DD Mon YYYY HH:MM:SS'
  • 它也适用于 Oracle。谢谢你:)
  • Oracle 使用的值如下:techonthenet.com/oracle/functions/to_date.php
  • 是的,对我来说格式正确 func.to_char(User.birthday, 'YYYY-MM-DD')
猜你喜欢
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 2016-03-08
  • 2014-06-23
相关资源
最近更新 更多