您可以使用pyodbc
Output Converter function
捕获从SQL Server返回的时间值并将其格式化为字符串。
之前:
import pyodbc
cnxn = pyodbc.connect('DSN=SQLmyDb;', autocommit=True)
crsr = cnxn.cursor()
rtn = crsr.execute("SELECT CAST('11:54:13.161' AS TIME)").fetchval()
print(repr(rtn)) # datetime.time(11, 54, 13, 161000)
crsr.close()
cnxn.close()
之后:
import pyodbc
import struct
def time_as_string(raw_bytes):
tup = struct.unpack("<4hI", raw_bytes) # e.g., (11, 54, 13, 0, 161000000)
tweaked = [tup[i] // 100 if i == 4 else tup[i] for i in [0, 1, 2, 4]]
return "{:02d}:{:02d}:{:02d}.{:07d}".format(*tweaked)
cnxn = pyodbc.connect('DSN=SQLmyDb;', autocommit=True)
cnxn.add_output_converter(pyodbc.SQL_SS_TIME2, time_as_string)
crsr = cnxn.cursor()
rtn = crsr.execute("SELECT CAST('11:54:13.161' AS TIME)").fetchval()
print(repr(rtn)) # '11:54:13.1610000'
crsr.close()
cnxn.close()