2016-06-24 31 views
0

使用連接到mssql數據庫的以下Python代碼並嘗試從數據庫中獲取數據。Python - 通過連接到MSSQL數據庫獲取數據的數據類型處理

import pymssql 
conn=pymssql.connect(host='localhost',user='sa',password='Password',database='HB') 
mycursor=conn.cursor() 
mycursor.execute("Select * from HB.dbo.TRANS") 
results=mycursor.fetchall() 
with open('Output.csv','w') as f: 
    for row in results: 
     print str(row) 
     s = ("%s\n" % str(row)) 
     f.write(s) 
f.close() 

獲取輸出:

(101, datetime.datetime(2016, 2, 1, 0, 0), 129.0, 0.0, 0.0, datetime.datetime(2016, 6, 22, 5, 50, 42, 83)) 

預期輸出:

(101, 2016:02:01 00:00:00.000, 129, 0, 0,2016:06:22 00:00:00.000, 5, 50, 42, 83) 

如何處理數據類型的數據取來了嗎? (即不想要的數據類型(datetime.datetime)出現在數據)

+0

你所說的「處理」是什麼意思? –

+0

按照處理,不希望數據類型出現在實際獲取的數據中。 –

回答

0

如果你想改變datetime.datetime()對象,你可以使用.strftime()方法

用法示例:

import datetime 
some_datetime = datetime.datetime.now() 
print(some_datetime) # will output: datetime.datetime(2016, 6, 24, 14, 57, 54, 190307) 
print(some_datetime.strftime("%Y-%m-%d %H:%M:%S")) # will output: 2016-06-24 14:58:53 

您可以考慮學習更多有關日期時間Python模塊here