python - 将excel导入mysql使用python并转换日期戳
问题描述
我需要 excel 中的数据 - date(20180301) 和 time(121220) 像这种 int 类型。我想将 excel 导入 mysql 使用 python 转换 datestamp (%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:类型对象'datetime.datetime'没有属性'formtimestamp'
解决方案
就像例外是什么一样'datetime.datetime' has no attribute '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.
推荐阅读
- r - 有没有办法在使用因子变量的填充选项的 ggplot 条形图上创建误差线?
- reactjs - 反应井字游戏
- javascript - 如何使用 Wordpress 中的方法防止 XSS 更改自定义全局 javascript 对象
- google-cloud-platform - 关于如何在Dataflow中读取GCS数据的问题
- c# - 具有潜在重定向的 HttpClient?
- python - 如何摆脱背包的蛮力?
- r - 如何用 rtweet 数据编织 Rmd?
- reactjs - 错误:应用程序(...):渲染没有返回任何内容。这通常意味着缺少返回语句 discord.js react typescript
- android - 如何让android更新“实际”当前位置?
- git - git remote -v 输出的详细信息