使用 pyscopg2 和 PostgreSQL 将日期时间插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30243530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting datetime into database using pyscopg2 and PostgreSQL
提问by Will Jones
I'm having trouble inserting a datetime stamp into a sql database using the insert statement with pyscopg2.
我在使用带有 pyscopg2 的插入语句将日期时间戳插入 sql 数据库时遇到问题。
What the code below does is every time the button is pushed, it should insert a row into the database containing the buildingID(which is just text) and the date and time when the button was pressed.
下面的代码所做的是每次按下按钮时,它应该在数据库中插入一行,其中包含建筑物 ID(它只是文本)以及按下按钮时的日期和时间。
I just can't figure out how to insert the current date and time.
我只是不知道如何插入当前日期和时间。
# 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()
回答by khampson
While you certainly couldinsert a Pythondatetime into a row via psycopg2-- you would need to create a datetime
object set to the current time, which can be done like thisor via modules such as Delorean-- since you just want the current time, I would just leave that up to Postgresitself.
虽然您当然可以通过psycopg2将Python日期时间插入到一行中——您需要创建一个设置为当前时间的对象,这可以像这样或通过诸如Delorean 之类的模块来完成——因为您只需要当前时间,我会把它留给Postgres本身。datetime
e.g.
例如
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()
returns the current time as a timestamp with time zone
type, and will be run on the server side after the first %s
is replaced by psycopg2(via libpq) by 01
.
now()
将当前时间作为timestamp with time zone
类型返回,并将在第一个%s
被psycopg2(通过libpq)替换后在服务器端运行01
。
Also note that the tupleof args must have a trailing comma since it has just one element, else it won't be an actual tuple.
还要注意args的元组必须有一个尾随逗号,因为它只有一个元素,否则它不会是一个实际的tuple。