【问题标题】:Python Pandas 0.14.0. Error with timestamp format when using dataframe.to_sqlPython 熊猫 0.14.0。使用 dataframe.to_sql 时时间戳格式出错
【发布时间】:2014-11-07 21:49:45
【问题描述】:

代码非常简单:

import Quandl
import sqlite3

myData = Quandl.get("DMDRN/AAPL_ALLFINANCIALRATIOS")

cnx = sqlite3.connect("APPL.db")
myData.to_sql('AAPL', cnx)

我打电话给Quandl API。它给了我一个熊猫数据框。 当我尝试将数据提交到 SQL 表时,我收到此错误

sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

索引是一个时间戳。

我试过这个 1-How to write Pandas dataframe to sqlite with Index 2- 将索引设置为其他值 + Convert numpy.datetime64 to string object in python

对于第一个,我仍然收到错误绑定参数 1 和 2 不起作用。

如果我想将数据框提交到 sqlite 表并将日期保留为索引,我应该怎么做(或最好的方法)。

【问题讨论】:

    标签: python sqlite numpy pandas quandl


    【解决方案1】:

    见pandas to_sql method gives error with date column

    问题是 sqlite 连接还不支持写入 datetime64 值。随着即将推出的 pandas 0.15,此错误将得到修复。 已经支持编写索引(从 pandas 0.14 开始),并且可以使用 index 关键字(默认为 True)进行控制。

    你有一些解决这个问题的选择:

    • 使用 sqlalchemy 来建立连接(你至少需要 0.14),因为它已经支持写入日期时间值:

      import sqlalchemy
      engine = sqlalchemy.create_engine('sqlite:///APPL.db')
      myData.to_sql('AAPL', engine, index=True)
      
    • 将日期时间索引转换为字符串(然后您可以继续直接使用 sqlite 连接)。你可以这样做:

      myData.index = myData.index.map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
      
    • 使用pandas开发版(https://github.com/pydata/pandas)

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2016-06-27
      • 1970-01-01
      • 2016-10-23
      • 2019-07-19
      • 2021-02-17
      • 2019-06-08
      • 2020-12-06
      • 2013-02-03
      相关资源
      最近更新 更多