2013-04-28 71 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