python-3.x - 为 "Sun, 17 Dec 2017 14:26:07 GMT"设置日期格式

标签 python-3.x postgresql psycopg2

我必须使用哪种 Postgres 日期类型来遵循日期格式?

Sun, 17 Dec 2017 14:26:07 GMT

我正在使用 TIMESTAMPTZ 并收到此错误:

Error: invalid input syntax for type timestamp with time zone: "p"
LINE 2:             VALUES ('h', 't', 't', ('p'), ('s'))
                                            ^

我应该在插入之前转换这样的日期吗?

最佳答案

您可能正在尝试将日期时间作为字符串插入。使用 datetime 对象和 let the database driver handle the type conversion automatically 进行参数化:

from datetime import datetime

date_string = "Sun, 17 Dec 2017 14:26:07 GMT"

dt = datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")

cursor.execute('INSERT INTO some_table (somecol) VALUES (%s)', (dt, ))

关于python-3.x - 为 "Sun, 17 Dec 2017 14:26:07 GMT"设置日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47862098/

相关文章:

sql - 选择行单元格作为新列

python - 从执行存储过程的 psycopg2 游标获取列名列表?

python - 检查并删除 DataFrame 的一系列行中的重复邻居值

django - 使用 Redis、Celery 设置 Django 以通过 Gmail 发送电子邮件

postgresql - Docker PostgreSQL-/docker-entrypoint-initdb.d 中的脚本不运行

postgresql - 复合唯一键的 Gorm 标签

python - 使用 python 插入 Postgres DB 列

psycopg2 - 为什么 psycopg2 不允许我们在同一连接中打开多个服务器端游标?

python - 如何从集合中删除多个元素?

python-3.x - 带单选按钮的 flask handle 形式