0

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(textcharactertimestamp without time zone. ...) But still Error:(

2
  • 1
    The problem is that the second argument to execute() is supposed to be a tuple. And even though you have (start_time) in parentheses, that does not make it a tuple. You need (start_time,) to make it a tuple. Commented Jul 15, 2022 at 4:17
  • 1
    This (start_time) is not correct. If you want a single element tuple it needs to be (start_time,). Note the ','. Commented Jul 15, 2022 at 4:17

1 Answer 1

0

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()

Sign up to request clarification or add additional context in comments.

2 Comments

No, this isn't the problem...
Thanks @JohnGordon and AdrianKlaver. . The tuple (value,) is a right way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.