我在excel中有一些数据要插入到MySQL表中。我把excel读入了Dataframe。数据包括一个日期列,其中包含我转换为datetime以匹配MySQL表设置的日期列( date列的类型为datetime)。当我试图将数据插入到表中时,会得到以下错误:
mysql.connector.errors.ProgrammingError:失败的处理格式-参数;Python时间戳不能转换为MySQL类型
当我打印日期后,转换它,我得到它的‘YYYY DD:MM:SS’格式,这似乎是MySQL需要的格式?
2011-05-10 : 00:00:00
可能做了一些简单的错事,但不能让这件事起作用。有什么建议吗?
表的SQL:
CREATE TABLE `Weight` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Date` datetime NOT NULL,
`Weight` float NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_c我的Python脚本,扩展到合并了一些虚拟数据:
import pandas as pd
import mysql.connector
import numpy as np
#import csv in dataframe
#df = pd.read_excel('/excel.xlsx')
#dataframe for this question on stackoverflow
startDate = '2011-05-03'
dateList = pd.date_range(startDate, periods=1000).tolist()
df = pd.DataFrame({'Day': dateList,
'Weight': np.random.normal(loc=68, scale=10, size=(1000,))
})
df['Day'] = pd.to_datetime(df['Day'],errors='raise')
mydb = mysql.connector.connect(
host="host",
user="user",
port="port",
passwd="Password",
database="database_name"
)
mycursor = mydb.cursor()
sql = "INSERT INTO Weight (Date, Weight) values (%s, %s)"
for index, row in df.iterrows() :
val = (row['Day'], row['Weight'])
mycursor.execute(sql, val)为了清楚起见,它在execute(sql,val)部分上失败
发布于 2018-10-30 11:22:33
使用@DeepSpace建议的df.to_sql解决了这个问题。
发布于 2021-08-08 12:32:42
另一个更简单的方法是将日期格式替换为excel文件中的文本。使用查找/替换:查找: 2011替换:'2011
发布于 2022-05-21 18:23:03
for index, row in df.iterrows() :
ts = row['Day']
ts = datetime(ts.year, ts.month, ts.day...) # ts.hour/min/sec if you have time info as well
val = (ts, row['Weight'])
mycursor.execute(sql, val)您需要将熊猫时间戳转换为!
https://stackoverflow.com/questions/53062493
复制相似问题