SQL Server DATE retrieved into pandas as a string

萝らか妹 提交于 2019-12-05 16:49:55

Use the parse_dates parameter of pandas.read_sql to specify that DateVar column values are explicitly converted to datetime on dataframe load.

Updated original code snippet:

...
d2 = pd.read_sql(sql=sql,
                 con=cnxn,
                 # explicitly convert DATE type to datetime object
                 parse_dates=["DateVar"])

cnxn.close()

print(d2.dtypes)

Returns

DateVar         datetime64[ns]
DateTimeVar     datetime64[ns]
DateTime2Var    datetime64[ns]
dtype: object

Tested with pyodbc 4.0.17, pandas 0.20.3, and SQL Server 2014 on Windows.

Try to use SQLAlchemy as follows:

from sqlalchemy import create_engine

engine = create_engine("mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=SQL+Server+Native+Client+10.0")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!