【问题标题】:datetime object in JSONB in PostgreSQLPostgreSQL 中 JSONB 中的日期时间对象
【发布时间】:2016-04-07 13:51:11
【问题描述】:

在使用 SQLAlchemy 的 PostgreSQL 9.5.2 中,JSONB 对象(一种用于存储 JSON 的结构化格式)中是否可以包含 datetime 对象。

from sqlalchemy.dialects.postgresql import JSONB
from datetime import datetime

class Object(Base):
    __tablename__ = 'object'
    id = Column(Integer, primary_key=True)
    attributes = Column(JSONB, nullable=False)

并插入到数据库中:

with transaction.manager:
    object = Object(attributes = {'name': 'miss piggy',
                                  'created': datetime.now()})
    session.add(object)
session.commit()

给我以下错误:

StatementError: (builtins.TypeError)
datetime.datetime(2016, 4, 7, 9, 51, 9, 893315) is not JSON serializable

[SQL: 'INSERT INTO object (attributes) VALUES (%(attributes)s)RETURNING object.id']
[parameters: [
    {'attributes': {'name': 'miss piggy',
                    'created': datetime.datetime(2016, 4, 7, 9, 51, 9, 893315)}}]]

【问题讨论】:

  • 不,不直接。你可以把它存储为一个字符串(或字典),然后做一些特殊的解析逻辑来确定它是一个日期时间。

标签: postgresql python-3.x datetime sqlalchemy jsonb


【解决方案1】:

为了解决这个问题,在univerio 的建议下,以下函数从日期时间对象创建字典,反之亦然:

def DictDatetime(t):
    dl = ['Y','m','d','H','M','S','f']
    if type(t) is datetime:
        return {a: t.strftime('%{}'.format(a)) for a in dl}
    elif type(t) is dict:
        return datetime.strptime(''.join(t[a] for a in dl),'%Y%m%d%H%M%S%f')

应用:

# Create datetime object
a = datetime.now()
# Convert datetime object to dictionary
b = DictDatetime(a)
# Convert dictionary to datetime object
c = DictDatetime(b)

检查:

a == c

返回:True

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2019-07-23
    • 1970-01-01
    • 2012-02-28
    相关资源
    最近更新 更多