使用 pyodbc 插入 SQL 服务器时出现日期列错误

Date column error when insert into SQL Server using pyodbc

我有一个 table Billing 其中有列

BILL_NO,CUSTOMER_NAME,PHONE_NO,BILLING_DATE,DELIVERY_DATE,TOTAL_AMOUNT

下面是推导 billing_dateDelivery_date 日期的逻辑。

orderdate = datetime.datetime.now().date()

if deliverydate != '':

     deliverydate = datetime.datetime.strptime(deliverydate,'%d/%m/%Y').date()
else:
     deliverydate = datetime.date(9999,12,31)

假设 delivery_date 值为 9999-12-31

我尝试将这些值加载到 SQL 服务器

ins_query = 'INSERT INTO dbo.BILLING VALUES(?,?,?,?,?,?)'

data = (billno,customername,phoneno,orderdate.strftime('%d/%m/%Y'),deliverydate.strftime('%d/%m/%Y'),totalamount)

cur.execute(ins_query,data)

但我收到以下有关日期列的错误

pyodbc.DataError: ('22007', '[22007]

[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when

converting date and/or time from character string. (241)

(SQLExecDirectW)')

如何格式化日期列以加载到 SQL 服务器。我希望将日期格式加载到数据库中,如 DD/MM/YYYYYYYY/MM/DD 格式

谢谢大家的建议。问题是我使用了旧的 OBDC sql 服务器连接。正如@bernie 所说,我们需要通过删除 .strptime() 将日期作为日期传递。即使我们使用它,我们也需要有最新的 odbc 驱动程序才能在 pyodbc 连接中使用。下面是解决问题的odbc驱动。

用于 SQL 服务器的 Microsoft ODBC 驱动程序 17

ins_query = 'INSERT INTO dbo.BILLING VALUES(?,?,?,?,?,?)'

data = (billno,customername,phoneno,orderdate,deliverydate,totalamount)

cur.execute(ins_query,data)