Python df.to_sql给出了带有dtype=sqlalchemy.timestamp(timezone=True)的TypeError

Python df.to_sql给出了带有dtype=sqlalchemy.timestamp(timezone=True)的TypeError,python,pandas,sqlalchemy,Python,Pandas,Sqlalchemy,我正在尝试使用DataFrame()来输入一个时间感知的数据帧序列。下面是我的代码示例 times = ['201412120154', '201412110254'] df = pd.DataFrame() df['time'] = pd.to_datetime(times, utc=True) df.time.to_sql('test', engine, dtype={'time': sqlalchemy.TIMESTAMP(timezone=True)}) 我收到

我正在尝试使用DataFrame()来输入一个时间感知的数据帧序列。下面是我的代码示例

times = ['201412120154', '201412110254']

df = pd.DataFrame()
df['time'] = pd.to_datetime(times, utc=True)

df.time.to_sql('test', engine, 
         dtype={'time': sqlalchemy.TIMESTAMP(timezone=True)})
我收到的错误是:

TypeError: issubclass() arg 1 must be a class
下面的代码可以工作,但显然会导致postgresql列不支持时区

times = ['201412120154', '201412110254']

df = pd.DataFrame()
df['time'] = pd.to_datetime(times, utc=True)

df.time.to_sql('test', engine, 
               dtype={'time': sqlalchemy.TIMESTAMP})

我正在使用python 2.7、pandas 0.15.2、postsgresql 9.3和SQLAlchemy 0.9.7更新:这在0.16中得到了修复

这是pandas 0.15.2中的一个错误,它妨碍您提供带有参数的实例化sqlalchemy类型(如
TIMESTAMP(timezone=True)
而不是
TIMESTAMP
)。这将在下一个版本中修复,但现在您可以使用下面的补丁


我也会在这里发布解决方法。如果运行此命令,您将能够在
to_sql
中指定用
dtype
关键字的参数实例化的sqlalchemy类型:

from pandas.io.sql import SQLTable

def to_sql(self, frame, name, if_exists='fail', index=True,
           index_label=None, schema=None, chunksize=None, dtype=None):
    """
    patched version of https://github.com/pydata/pandas/blob/v0.15.2/pandas/io/sql.py#L1129
    """
    if dtype is not None:
        from sqlalchemy.types import to_instance, TypeEngine
        for col, my_type in dtype.items():
            if not isinstance(to_instance(my_type), TypeEngine):
                raise ValueError('The type of %s is not a SQLAlchemy '
                                 'type ' % col)

    table = SQLTable(name, self, frame=frame, index=index,
                     if_exists=if_exists, index_label=index_label,
                     schema=schema, dtype=dtype)
    table.create()
    table.insert(chunksize)

pd.io.sql.SQLDatabase.to_sql = to_sql

你能在问题追踪器上报告吗?好的,添加到问题跟踪器,如果在那里解决了,我一定会在这里更新它。joris很友好地提供了一个解决方案,直到这个bug被修复为止,这个bug是为pandas 0.16.0设计的。