PostgreSQL — Обновление даты и времени без часового пояса

#python #postgresql #datetime #sqlalchemy

Вопрос:

Я пытаюсь заменить значение даты и времени в базе данных PostgreSQL без часового пояса;

 from sqlalchemy import create_engine

# Connection with DB
engine = create_engine('postgresql://postgres:xxx')

engine.connect()

# Select Values
batch_id = 15
correct_datetime = pd.to_datetime('2021-10-05' , format='%Y-%m-%d')

# Perform update
sql = f"""
    UPDATE my_table
    SET datetime_opening={correct_datetime}
    WHERE id={batch_id}
"""

with engine.begin() as conn:     # TRANSACTION
    conn.execute(sql)
 

Однако это вызывает следующую ошибку:

 (psycopg2.errors.SyntaxError) syntax error at or near "00"
LINE 3: ...   SET datetime_opening=2021-10-05 00:00:00
 

Другие испытания включают:

 # 1
correct_datetime = '2021-10-05'
ProgrammingError: (psycopg2.errors.DatatypeMismatch) column "datetime_opening" is of type timestamp without time zone but expression is of type integer
LINE 3:     SET datetime_opening=2021-10-05
                                                  ^
HINT:  You will need to rewrite or cast the expression.

# 2
correct_datetime = df.iloc[-1, 6]   timedelta(days=7)
ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "18"
LINE 3: ...   SET datetime_opening=2021-10-05 18:00:00
 

Как я могу правильно обновить значение с помощью новой даты и времени?

Ответ №1:

Единственное различие, которое необходимо реализовать, — это заменить {correct_datetime} на » {correct_datetime}».

Таким образом,

 correct_datetime = '2021-10-05'


# Perform update
sql = f"""
    UPDATE my_table
    SET datetime_opening ='{correct_datetime}'
    WHERE id={batch_id}
"""