使用 pyscopg2 和 PostgreSQL 将日期时间插入数据库
Inserting datetime into database using pyscopg2 and PostgreSQL
我在使用 pyscopg2 的插入语句将日期时间戳插入 sql 数据库时遇到问题。
下面的代码所做的是每次按下按钮时,它应该在数据库中插入一行,其中包含建筑物 ID(只是文本)以及按下按钮的日期和时间。
我只是不知道如何插入当前日期和时间。
# 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()
虽然你当然 可以 通过 psycopg2[=34 将 Python 日期时间插入一行=] -- 你需要创建一个设置为当前时间的 datetime
对象,这可以完成 like this or via modules such as 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()
returns 当前时间为 timestamp with time zone
类型,将第一个 %s
替换为 运行 在服务器端psycopg2(通过 libpq)由 01
.
另请注意,args 的 tuple 必须有一个尾随逗号,因为它只有一个元素,否则它不会是一个实际的 tuple.
我在使用 pyscopg2 的插入语句将日期时间戳插入 sql 数据库时遇到问题。
下面的代码所做的是每次按下按钮时,它应该在数据库中插入一行,其中包含建筑物 ID(只是文本)以及按下按钮的日期和时间。
我只是不知道如何插入当前日期和时间。
# 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()
虽然你当然 可以 通过 psycopg2[=34 将 Python 日期时间插入一行=] -- 你需要创建一个设置为当前时间的 datetime
对象,这可以完成 like this or via modules such as 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()
returns 当前时间为 timestamp with time zone
类型,将第一个 %s
替换为 运行 在服务器端psycopg2(通过 libpq)由 01
.
另请注意,args 的 tuple 必须有一个尾随逗号,因为它只有一个元素,否则它不会是一个实际的 tuple.