使用pyscopg2和PostgreSQL将日期时间插入数据库

7
我在使用pyscopg2中的插入语句向SQL数据库中插入日期时间戳时遇到了问题。
以下代码每次按下按钮时应将包含buildingID(仅为文本)和按下按钮时的日期和时间的行插入数据库中。
我无法弄清如何插入当前日期和时间。
# Inserts data into local database
def insertLocalDB():
    # Open a cursor to perform database operations
    cur = conn.cursor()
    cur.execute("INSERT INTO test_table (buildingID,datetime) VALUES(%s,%s)",
    ("01", datetime))  #HAS TO BE CURRENT DATE AND TIME
    # Make the changes to the database persistant
    conn.commit()
    # Close communication with the database
    cur.close()
1个回答

16
虽然您可以通过使用psycopg2Python日期时间插入行中,但是您需要创建一个设置为当前时间的datetime对象,可以通过如此或通过诸如Delorean等模块来完成。但由于您只需要当前时间,我建议让Postgres自己处理。
例如:
def insertLocalDB():
    # Open a cursor to perform database operations
    cur = conn.cursor()
    cur.execute("INSERT INTO test_table (buildingID,datetime) VALUES(%s, now() )",
    ("01", ))
    # Make the changes to the database persistant
    conn.commit()
    # Close communication with the database
    cur.close()

now() 返回当前时间,类型为 timestamp with time zone,并且会在第一个 %spsycopg2(通过 libpq)替换为 01 后在服务器端运行。

另外请注意,由于参数只有一个元素,所以参数的元组必须有一个尾随逗号,否则它不是一个真正的元组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接