导入excel到mysql使用python并转换时间戳

问题描述 投票:0回答:1

我需要excel中的数据 - 日期(20180301)和时间(121220),就像这个int类型一样。我想导入excel到mysql使用python转换datestamp(%t-%m-%d%H:%M:%S)为一个coulm。

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:类型对象'datetime.datetime'没有属性'formtimestamp'

python mysql
1个回答
0
投票

正如异常一样,'datetime.datetime' has no attribute 'formtimestamp',因为它应该是fromtimestamp(看到区别?)。而且,你可以使用'pandas'模块处理数据工作。

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.
© www.soinside.com 2019 - 2024. All rights reserved.