I want to insert datetime into postgres via python
from datetime import datetime, timedelta
start_time_format = datetime.now() - timedelta(hours =33)
start_time = start_time_format.strftime("%Y-%m-%d %H:%M")
conn = psycopg2.connect(...*connect postgresql*..)
cursor = conn.cursor()
cursor.execute("""INSERT INTO table01(start_time_str) VALUES(%s);""", (start_time))
conn.commit()
I get the following error:
cursor.execute("""INSERT INTO table01(start_time_str) VALUES(%s);""", (start_time))
TypeError: not all arguments converted during string formatting
I try to change other DataType(text
、character
、timestamp without time zone
. ...)
But still Error:(
CodePudding user response:
Rectifying my previous response after reading comments from @AdrianKlaver and @JohnGordon. There comments should be taken as the correct answer, I am just modifying my response so that future readers do the right thing
cursor.execute("""INSERT INTO table01(start_time_str) VALUES(%s);""", (start_time,))
As @AdrianKlaver and @JohnGordon mentioned, just watch out for the ',' in (start_time,) to pass it as a tuple to the cursor.execute()