python - PostgreSQL - 更新没有时区的日期时间
问题描述
我正在尝试在没有时区的 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
如何使用新的日期时间正确更新值?
解决方案
要实现的唯一区别是将 {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}
"""
推荐阅读
- javascript - JavaScript - 递归方式的步骤算法 - 多循环问题
- sql - Microsoft SQL Server 和 Oracle SQL Developer
- lua - corona sdk(lua)中的分数函数问题
- c# - 在令牌不再使用后调用 CancellationToken 注册的回调
- java - Java Play 框架“java.util.NoSuchElementException:调用 setControllerComponents...”
- python - AttributeError:“str”对象在最后一行没有属性“write”错误,需要洞察力
- go - 无法调用 go-gin 中间件
- tensorflow - 为什么 Bert 转换器使用 [CLS] 令牌进行分类,而不是对所有令牌进行平均?
- python - 从同一网络上的其他设备连接到 Flask Server
- go - 在 Linux/macOS 终端中从 Go 程序打印并使用回车时清除其余行