我正在使用psycopg2的CURRENT_TIMESTAMP
关键字来分配我的SQL对象的creationDate
属性:
def createDuck(data):
""" Creates a new ducky in the Duck table. """
keys = ['color', 'species', 'numberOfFeathers', 'creationDate']
# Insert all values except the last one because it's the date
dataToInsert = [data.get(k) for k in keys[:-1] ]
with transaction() as (conn, cur):
query = sql.SQL('INSERT INTO {} ({}) VALUES ({}, CURRENT_TIMESTAMP) RETURNING id;').format(
sql.Identifier('Duck'),
sql.SQL(', ').join(map(sql.Identifier, keys )),
sql.SQL(', ').join(map(sql.Literal, dataToInsert))
)
cur.execute(query)
return cur.fetchone()['id']
到目前为止,运行这个代码片段会创建一个duck,creationDate
看起来像一个日期:2019-06-26 14:29:23.480065+00
现在我需要用SQL duck表中的数据创建一个duck作为python对象。你知道吗
所以我调用我所有的鸭子,把它们放在一个列表中,然后为每个列表条目创建它的python twin:
def getAllDucks(self):
with transaction() as (conn,cur):
query = sql.SQL('SELECT * FROM {};').format(
sql.Identifier('Ducks')
)
cur.execute(query)
ducksInTable = cur.fetchall()
listOfDucks = []
for row in ducksInTable:
ducky = Duck(dict(row))
listOfDucks.append(ducky)
return listOfDucks
然而,这里的问题是,当我打印ducks的所有属性时,creationDate
现在看起来是这样的:
datetime.datetime(2019, 6, 26, 14, 29, 23, 480065, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))
现在我明白了CURRENT_TIMESTAMP
是PostgreSQL的一个特殊关键字。但是我需要在python列表中显示日期,就像在SQL表中一样。你知道吗
在打印Python鸭列表时,有没有办法像PostgreSQL那样显示creationDate
?
我曾想过打印自己的函数,但如果python中还没有这样的功能,我会感到惊讶。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐