psycopg2 选择时间戳 returns datetime.datetime 包裹在元组中,如何解包?

psycopg2 selecting timestamp returns datetime.datetime wrapped in tuple, how to unpack?

我创建了一个 table:

 cursor.execute("CREATE TABLE articles (title varchar PRIMARY KEY, pubDate timestamp with time zone);")

我插入了这样的时间戳:

timestamp = date_datetime.strftime("%Y-%m-%d %H:%M:%S+00")

cursor.execute("INSERT INTO articles VALUES (%s, %s)", 
              (title, timestamp))

当我 运行 一个 SELECT 语句来检索时间戳时,它 returns 元组代替:

cursor.execute("SELECT pubDate FROM articles")
rows = cursor.fetchall()
for row in rows:
    print(row)

这是返回的行:

(datetime.datetime(2015, 12, 9, 6, 47, 4, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=660, name=None)),)

如何直接检索日期时间对象?

我已经查找了一些其他相关问题(请参阅 and ),但似乎找不到答案。可能在这里忽略了一些简单的事情,但我们将不胜感激!

经过更多的谷歌搜索,我想我明白了。如果我改变:

print(row)

print(row[0])

它确实有效。我想这是因为行是一个元组,这是正确解压元组的方法。

Python的datetime对象被psycopg2自动adapted变成SQL,你不需要将它们字符串化:

cursor.execute("INSERT INTO articles VALUES (%s, %s)", 
               (title, datetime_obj))

要读取 SELECT 返回的行,您可以将游标用作迭代器,根据需要解包行元组:

cursor.execute("SELECT pubDate FROM articles")

for pub_date, in cursor:  # note the comma after `pub_date`
    print(pub_date)
import pytz

title ='The Title'
tz = pytz.timezone("US/Pacific")
timestamp = tz.localize(datetime(2015, 05, 20, 13, 56, 02), is_dst=None)

query = "insert into articles values (%s, %s)"
print cursor.mogrify(query, (title, timestamp))
cursor.execute(query, (title, timestamp))
conn.commit()

query = "select * from articles"
cursor.execute(query)
rs = cursor.fetchall()[0]
print rs[0], rs[1]
print type(rs[1])

输出:

insert into articles values ('The Title', '2015-05-20T13:56:02-07:00'::timestamptz)
The Title 2015-05-20 17:56:02-03:00
<type 'datetime.datetime'>