postgres / psycopg:导入 CSV 的日期格式错误

postgres / psycopg: Date format error importing CSV

我在 python 3.10 中使用 psycopg (v3),在 Pycharm 中工作。我做了一个 table 并试图导入一个 .csv;我收到此错误:

invalid input syntax for type date: "01/31/22"

CONTEXT: COPY test_table, line 1, column quote_date: "01/31/22"

首先我认为 DateStyle 不正确所以我添加:

cur.execute('SET DateStyle = "ISO, MDY";')

这是我的完整代码:

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)

我仍然遇到同样的错误。我在文本编辑器中检查了 .csv,它看起来不错。
(目录中的'...'在此被截断post)

我想你想要 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)

还有“22”?难道我们没有从 Y2K 的混乱中学到什么吗?

在我的例子中有效:

    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)

但我用 psycopg2 代替 psycopg。我的 dt.csv 文件也有 header:

dt
01/31/22
02/22/23

所以我添加了HEADER true。 table

的 DDL
CREATE TABLE test_table(
    dt DATE
)

PostgreSQL 11.4,psycopg2==2.8.6

pgAdmin 中的结果 table: