0

I cannot write date into Postgres column with type 'date'.

I use this code:

import datetime
import pytz

now = datetime.datetime.now(pytz.timezone("Europe/Moscow"))
sql = "INSERT INTO questions (date) VALUES (%s, %s)" \
                      % (datetime.date(now.year, now.month, now.day))
cursor.execute(sql)

Also, I tried this:

sql = "INSERT INTO questions (date) VALUES (%s, %s)" \
                      % (datetime.datetime.now())
cursor.execute(sql)

But I have the same error:

psycopg2.errors.DatatypeMismatch: ╬╪╚┴╩└:  ёЄюысхЎ "date" шьххЄ Єшя date, р т√Ёрцхэшх - integer
LINE 1: INSERT INTO questions (id, date) VALUES (10, 2020-12-04)
                                                     ^
HINT:  ╧хЁхяш°шЄх т√Ёрцхэшх шыш яЁхюсЁрчєщЄх хую Єшя.

Can you help me, what's the problem?

2
  • 3
    Do not insert your values into the sql string. (There's good reasons for never doing this; google sql injection...) Try instead: cursor.execute(sql, (datetime.datetime.now(), (datetime.datetime.now())) Commented Dec 4, 2020 at 18:45
  • 3
    Please check the docs psycopg.org/docs/usage.html#passing-parameters-to-sql-queries. As paul comments, you should not use string formatting/interpolation to create SQL queries unless you understand all the rules around quoting variables. Chances are postgres thinks 2020-12-04 is an arithmetic expression. Commented Dec 4, 2020 at 18:48

1 Answer 1

1

Date type is actually a custom type of the String. So date value should be string.

Try this (which added 2 ' characters.):

sql = "INSERT INTO questions (id, date) VALUES (%s, '%s')" % (datetime.datetime.now())

Note: Check the paul's comment also!

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

1 Comment

See the comments on the answer about not inserting values directly into SQL strings. This can be a very severe security vulnerability.

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.