Wil*_*nes 5 postgresql psycopg2
我使用带pyscopg2的insert语句将日期时间戳插入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()
Run Code Online (Sandbox Code Playgroud)
kha*_*son 12
虽然您当然可以通过psycopg2将Python日期时间插入到一行中- 您需要创建一个设置为当前时间的对象,这可以像这样或通过诸如Delorean之类的模块完成- 因为您只需要当前时间,我会把它留给Postgres本身.datetime
例如
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()
Run Code Online (Sandbox Code Playgroud)
now()将当前时间作为timestamp with time zone类型返回,并在第一个%s被psycopg2(通过libpq)替换之后在服务器端运行01.
另请注意,args 的元组必须有一个尾随逗号,因为它只有一个元素,否则它不会是一个实际的元组.
| 归档时间: |
|
| 查看次数: |
9428 次 |
| 最近记录: |