使用python将excel导入mysql并转换日期戳

使用python将excel导入mysql并转换日期戳,python,mysql,Python,Mysql,我需要excel中的数据-日期(20180301)和时间(121220)像这样的int类型。 我希望将excel导入mysql,使用python转换日期戳(%t-%m-%d%H:%m:%S)进行一次导入 import xlrd import pymysql import time import datetime #open the workbook and define rhe worksheet book = xlrd.open_workbook("d:/waiting2.xlsx") sh

我需要excel中的数据-日期(20180301)和时间(121220)像这样的int类型。 我希望将excel导入mysql,使用python转换日期戳(%t-%m-%d%H:%m:%S)进行一次导入

import xlrd
import pymysql
import time
import datetime
#open the workbook and define rhe worksheet
book  = xlrd.open_workbook("d:/waiting2.xlsx")
sheet = book.sheet_by_index(0)
ts = time.time()
timestamp = datetime.datetime.formtimestamp(ts).strftime('%t-%m-%d %H:%M:%S')
#sheet = book.sheet_by_index(0)

#establish a mysql connection
database = pymysql.connect(host="localhost", user='root', password='1234',db='test')

#get the cursor, which is used to traverse the database, line by line
cursor = database.cursor()

try:
    cursor.execute("""INSERT into test(date+time) values($s)""", (timestamp))
    database.commit()
except:
    database.rollback()

database.close()

AttributeError:type对象“datetime.datetime”没有属性“formtimestamp”

正如例外情况一样,
“datetime.datetime”没有属性“formtimestamp”
,因为它应该是
fromtimestamp
(看到区别了吗?)。 此外,您还可以使用“熊猫”模块处理数据工作

import pandas as pd
df = pd.read_excel('d:/waiting2.xlsx')
from sqlalchemy import create_engine
connect = create_engine('mysql+pymysql://root:root@localhost:3306/test')
# assume that you are using mysql as your DBM and 3306 as the port.
df.to_sql('test', connect, index=False, if_exists='append')
# and before this you should convert datatime string yourself.

为什么需要使用Python?尝试将数据直接从Excel加载到MySQL会有什么问题?我尝试connect=create\u engine('MySQL+mysqldb://root:PW@localhost:3306/test'),但“ModuleNotFoundError:没有名为'MySQLdb'的模块”中出现错误。所以我安装了mysqldb,但找不到一个版本…我如何修复?您使用的是哪个版本的python?如果您使用的是python3,您可以尝试使用pymysql。使用python3.6版本,我安装pymysql。您需要将连接url改为pymysql,sqlalchemy不会自动使用pymysql,这意味着
connect=create\u engine('mysql+pymysql://root:PW@localhost:3306/test')
(请记住将PW和root更改为您自己的密码和用户名。)