2015-05-14 64 views
1

我在使用pyscopg2插入语句将日期时间戳插入sql数据库时遇到了问题。使用pyscopg2和PostgreSQL将datetime插入到数据库中

以下代码所做的每次按下按钮时,都应该在包含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() 

回答

7

虽然你肯定可以通过psycopg2插入的Python日期时间成一排 - 你需要创建一个datetime对象设置为当前时间,这是可以做到like this或通过模块例如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类型,并且将在服务器侧的第一%s后由01取代psycopg2(经由的libpq)上运行。

另外请注意,args来元组必须有一个尾随逗号,因为它有一个元素,否则它不会是一个实际的元组

相关问题