psycopg2选择timestamp返回datetime.datetime包装成元组,如何解包?

2024-06-01 18:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个表:

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

如何直接检索datetime对象?

我查了一些其他相关的问题(见herehere),但似乎找不到答案。可能忽略了一些简单的事情,但任何帮助将非常感谢!


Tags: executedatetimeheretitlecreate时间tableselect
3条回答

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)

再搜了几下,我想我找到了。如果我改变:

print(row)

print(row[0])

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

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

相关问题 更多 >