gpt4 book ai didi

python - psycopg2 选择时间戳返回包裹在元组中的 datetime.datetime,如何解包?

转载 作者:太空狗 更新时间:2023-10-30 00:44:06 25 4
gpt4 key购买 nike

我创建了一个表:

 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),但似乎找不到答案。可能在这里忽略了一些简单的事情,但我们将不胜感激!

最佳答案

Python 的datetime 对象自动为adapted通过 psycopg2 进入 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)

关于python - psycopg2 选择时间戳返回包裹在元组中的 datetime.datetime,如何解包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34178172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com