【问题标题】:MS SQL time datatype to python timeMS SQL时间数据类型到python时间
【发布时间】:2015-06-16 13:49:05
【问题描述】:

如何将 MSSQL 时间数据类型转换为 python 时间或字符串? MSSQL 服务器中的列定义为 time(7)。

在 Windows7 上,我使用的是 Python3/adodbapi,列返回为字节:

sql = 'SELECT top 1 * FROM table1'
with adodbapi.connect('srv') as cn:
    with cn.cursor() as cur:
        cur.execute(sql)
        for row in cur:
            print(type(row['col1']))
            print(row['col1'])
            for c in row['col1']: print(c)

>>> <class 'bytes'>
>>> b'\t\x00\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> 9
    0
    30
    0
    0
    0
    0
    0
    0
    0
    0
    0 

如何将 python 字节转换回时间或字符串?

在 linux 上,我使用的是 Python3/pymssql,列返回为字符串,我可以将其解析为时间。

>>> <class 'str'>
>>> 09:30:00.0000000

【问题讨论】:

  • 也许这个答案可以帮助你:stackoverflow.com/questions/20024490/…
  • 我最终用 convert(smalldatetime, col1) as time1 调整了 sql 语句
  • 如果您已经设法自己解决了您的问题,请详细说明您做了什么作为答案,以便未来的读者可以从中受益。您也可以接受自己的答案。

标签: python sql-server time


【解决方案1】:

我的解决方法是调整 sql 语句,以便 tsql 显式转换 time() 列:

sql = 'SELECT *, convert(smalldatetime, col1) as ncol1  FROM table1'

在 windows(adodbapi) 和 linux(pymssql) 上,我现在都在为 'ncol1' 获得一致的 python 日期时间对象。

更新: 它看起来像一个数据库驱动程序问题。在 Windows 上切换到 pymssql 后,我发现数据库中的 time(7) 列也以字符串形式返回,与 Linux 上的相同。 (所以Linux/windows pymssql 都返回String 为时间列,这是一致的。)由于某种原因,adodbapi 返回了bytearray。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多