2016-04-07 66 views
2

PostgreSQL 9.5.2中有沒有可能在JSONB對象(用於存儲JSON的結構化格式)中有datetime對象和SQLAlchemy。PostgreSQL中的JSONB中的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)}}]] 
+0

不,不是直接。你可以將它存儲爲一個字符串(或字典),然後做一些特殊的解析邏輯來確定它是一個日期時間。 – univerio

回答

0

爲了解決這個問題,用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