[英]postgres / psycopg: Date format error importing CSV
I'm using psycopg (v3) in python 3.10, working in Pycharm. I made a table and am trying to import a.csv;我在 python 3.10 中使用 psycopg (v3),在 Pycharm 中工作。我制作了一张表并尝试导入 a.csv; I'm getting this error:
我收到此错误:
invalid input syntax for type date: "01/31/22"
类型日期的无效输入语法:“01/31/22”
CONTEXT: COPY test_table, line 1, column quote_date: "01/31/22"
上下文:复制测试表,第 1 行,列 quote_date:“01/31/22”
First I thought the DateStyle was incorrect so I added:首先我认为 DateStyle 不正确所以我添加:
cur.execute('SET DateStyle = "ISO, MDY";')
Here's my full code:这是我的完整代码:
import psycopg
from config import config
# Connect to an existing database
try:
params = config()
with psycopg.connect(**params) as conn:
# Open a cursor to perform database operations
with conn.cursor() as cur:
cur.execute('SELECT version()')
db_version = cur.fetchone()
print(f'PostgreSQL database version: {db_version}')
print('Connected to database.')
cur.execute('SET DateStyle = "ISO, MDY";')
cur.execute("""
COPY test_table
FROM '/Users/.../copy.csv'
DELIMITER ',';""")
except(Exception, psycopg.DatabaseError) as error:
print(error)
I'm still getting the same error.我仍然遇到同样的错误。 I checked the.csv in a text editor and it looks fine.
我在文本编辑器中检查了 .csv,它看起来不错。
(The '...' in the directory was truncated in this post) (目录中的“...”在这篇文章中被截断了)
I think you want SQL
, not ISO
:我想你想要
SQL
,而不是ISO
:
db=> SET datestyle='SQL, MDY';
SET
db=> SELECT to_char('2/17/22'::DATE, 'day dd month YYYY') ;
to_char
-----------------------------
thursday 17 february 2022
(1 row)
And "22"?还有“22”? Didn't we learn anything from the Y2K mess?
难道我们没有从 Y2K 混乱中学到任何东西吗?
In my case it works:就我而言,它有效:
import psycopg2
try:
with psycopg2.connect(
dbname="postgres",
user="postgres",
password="password",
host="localhost",
port=54321,
) as conn:
# Open a cursor to perform database operations
with conn.cursor() as cur:
cur.execute('SELECT version()')
db_version = cur.fetchone()
print(f'PostgreSQL database version: {db_version}')
print('Connected to database.')
cur.execute('SET DateStyle = "ISO, MDY";')
cur.execute("""
COPY test_table
FROM '/tmp/dt.csv'
(FORMAT csv, DELIMITER ',', HEADER true);""")
except(Exception, psycopg2.DatabaseError) as error:
print(error)
But i used psycopg2
instead psycopg
.但我使用
psycopg2
而不是psycopg
。 Also my dt.csv
file has header:我的
dt.csv
文件也有 header:
dt
01/31/22
02/22/23
So i added HEADER true
.所以我添加了
HEADER true
。 DDL for table表的 DDL
CREATE TABLE test_table(
dt DATE
)
PostgreSQL 11.4, psycopg2==2.8.6 PostgreSQL 11.4,psycopg2==2.8.6
Result table in pgAdmin: pgAdmin 中的结果表:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.