psycopg2选择时间戳返回包含在元组中的datetime.datetime,如何解压缩?

时间:2015-12-09 11:52:01

标签: python datetime tuples psycopg2

我创建了一个表:

 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语句来检索时间戳时,它会返回元组:

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)),)

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

我查了几个其他相关问题(请参阅herehere),但似乎无法找到答案。可能会忽略一些简单的东西,但任何帮助都会非常感激!

3 个答案:

答案 0 :(得分:7)

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)

答案 1 :(得分:2)

经过一些谷歌搜索后,我想我已经弄明白了。如果我改变:

print(row)

print(row[0])

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

答案 2 :(得分:0)

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'>