Mary Smith
Mary Smith

Reputation: 451

How to write current date into Postgres with Python?

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?

Upvotes: 0

Views: 2235

Answers (1)

ishak O.
ishak O.

Reputation: 191

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!

Upvotes: 1

Related Questions