2013-04-28 69 views
1

我正在使用字符串模板漂亮地打印cur.fetchall()來自MySQL數據庫的數據。元組中的datetime對象與模板無法正確打印

一個典型的元組是這樣的:

(('DL2C1683', 'in', datetime.datetime(2013, 4, 28, 15, 53, 27), 'hyundai i10', '11'), ('UP1S1783', 'in', datetime.datetime(2013, 4, 28, 15, 53, 57), 'honda kinetic', '11')) 

我用下面的代碼打印此元組:

template = "{0:15}|{1:15}|{2:15}|{3:15}|{4:15}" 
print template.format("Registration No.", "State", "Time", "Make", "Sector") # header 
for row in rows: 
    print template.format(*row) 

DateTime對象不打印,我不是得到,同樣在標題之後,下面的行沒有正確對齊。

輸出:

Registration No.|State   |Time   |Make   |Sector   
DL2C1683  |in    |15|hyundai i10 |11    
UP1S1783  |in    |15|honda kinetic |11  
+0

好了,的取向的問題之一是,因爲'「登記號」'具有16個字符,並你只分配了15. – Aya 2013-04-28 11:22:24

+0

@Aya這不僅僅是,看看這兩個'15's – jamylak 2013-04-28 11:24:32

+0

@Aya這解釋了對齊問題,我想:)謝謝,但日期時間仍然沒有打印。 – 2013-04-28 11:26:23

回答

3

使用一些大的寬度例如。 25還要加!s.format轉換標誌來強制datetimestr

import datetime 
template = "{0:25}|{1:25}|{2!s:25}|{3:25}|{4:25}" 
rows = (('DL2C1683', 'in', datetime.datetime(2013, 4, 28, 15, 53, 27), 'hyundai i10', '11'), 
     ('UP1S1783', 'in', datetime.datetime(2013, 4, 28, 15, 53, 57), 'honda kinetic', '11')) 
print template.format("Registration No.", "State", "Time", "Make", "Sector") # header 
for row in rows: 
    print template.format(*row) 

Registration No.   |State     |Time      |Make      |Sector     
DL2C1683     |in      |2013-04-28 15:53:27  |hyundai i10    |11      
UP1S1783     |in      |2013-04-28 15:53:57  |honda kinetic   |11   
+0

是的,它現在工作,我實際上不知道如何把轉換標誌! – 2013-04-28 11:31:38