【发布时间】:2019-04-11 23:42:42
【问题描述】:
我正在尝试将带有毫秒时间戳的 DataFrame 获取到 MySQL 数据库中。但是,这样做时,毫秒部分似乎被丢弃了。我创建了一个工作示例来展示发生了什么:
import pandas as pd
from sqlalchemy import create_engine # database connection
#Generate date_time with millisecond resolution and price column
df=pd.DataFrame({'date_time' : pd.date_range('1/1/2000 09:00:00', freq="5ms",periods=100),'price' : np.random.random_sample(100)})
#Connect with an empty MySQL database (which I simply created using CREATE DATABASE trading_db;)
disk_engine = create_engine("mysql+mysqldb://root:"+'MYPASSWORD'+"@localhost/trading_db")
#Dataframe to SQL in a Table called trading_data
df.to_sql('trading_data', disk_engine, if_exists='replace',index=False)
#When I read this back from MySQL, the milliseconds seem to dissapear
df_sql = pd.read_sql_query('SELECT *'
'FROM trading_data '
'LIMIT 20', disk_engine)
比较在pandas 中创建的DataFrame 的日期时间与从MySQL 加载的日期时间:
df.head()
date_time price
0 2000-01-01 09:00:00 0.371986
1 2000-01-01 09:00:00.005000 0.625551
2 2000-01-01 09:00:00.010000 0.631182
3 2000-01-01 09:00:00.015000 0.625316
4 2000-01-01 09:00:00.020000 0.522437
df_sql.head()
date_time price
0 2000-01-01 09:00:00 0.371986
1 2000-01-01 09:00:00 0.625551
2 2000-01-01 09:00:00 0.631182
3 2000-01-01 09:00:00 0.625316
4 2000-01-01 09:00:00 0.522437
您可以清楚地看到毫秒数减少了。有什么办法可以更改代码以保留毫秒部分?
编辑:我正在使用 MySQL Workbench 6.2 和 pandas 0.14.1
【问题讨论】:
-
您需要在v5.6.4+ 上才能支持小数时间值。