[英]postgres / psycopg: Date format error importing CSV
我在 python 3.10 中使用 psycopg (v3),在 Pycharm 中工作。我制作了一張表並嘗試導入 a.csv; 我收到此錯誤:
類型日期的無效輸入語法:“01/31/22”
上下文:復制測試表,第 1 行,列 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,它看起來不錯。
(目錄中的“...”在這篇文章中被截斷了)
我想你想要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
。 表的 DDL
CREATE TABLE test_table(
dt DATE
)
PostgreSQL 11.4,psycopg2==2.8.6
pgAdmin 中的結果表:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.