psycopg2 - Inserting datetime into database using pyscopg2 and PostgreSQL -
i'm having trouble inserting datetime stamp sql database using insert statement pyscopg2.
what code below every time button pushed, should insert row database containing buildingid(which text) , date , time when button pressed.
i can't figure out how insert current date , time.
# inserts data local database def insertlocaldb(): # open cursor perform database operations cur = conn.cursor() cur.execute("insert test_table (buildingid,datetime) values(%s,%s)", ("01", datetime)) #has current date , time # make changes database persistant conn.commit() # close communication database cur.close()
while could insert python datetime row via psycopg2 -- need create datetime object set current time, can done like this or via modules such delorean -- since want current time, leave postgres itself.
e.g.
def insertlocaldb(): # open cursor perform database operations cur = conn.cursor() cur.execute("insert test_table (buildingid,datetime) values(%s, now() )", ("01", )) # make changes database persistant conn.commit() # close communication database cur.close() now() returns current time timestamp time zone type, , run on server side after first %s replaced psycopg2 (via libpq) 01.
also note tuple of args must have trailing comma since has 1 element, else won't actual tuple.
Comments
Post a Comment