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

fre*_*all 5 python datetime tuples psycopg2

我创建了一个表:

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

我插入了一个这样的时间戳:

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

cursor.execute("INSERT INTO articles VALUES (%s, %s)", 
              (title, timestamp))
Run Code Online (Sandbox Code Playgroud)

当我运行SELECT语句来检索时间戳时,它会返回元组:

cursor.execute("SELECT pubDate FROM articles")
rows = cursor.fetchall()
for row in rows:
    print(row)
Run Code Online (Sandbox Code Playgroud)

这是返回的行:

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

如何直接检索datetime对象?

我查了几个其他相关的问题(见这里这里),但似乎找不到答案.可能会忽略这里简单的东西,但任何帮助将不胜感激!

Eug*_*ash 7

Python的datetime对象会自动适应 SQL psycopg2,您不需要对它们进行字符串化:

cursor.execute("INSERT INTO articles VALUES (%s, %s)", 
               (title, datetime_obj))
Run Code Online (Sandbox Code Playgroud)

要读取a返回的行,SELECT可以使用游标作为迭代器,根据需要解压缩行元组:

cursor.execute("SELECT pubDate FROM articles")

for pub_date, in cursor:  # note the comma after `pub_date`
    print(pub_date)
Run Code Online (Sandbox Code Playgroud)