元组中的datetime对象未使用temp正确打印

2024-10-03 02:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用字符串模板从MySQL数据库中打印cur.fetchall()数据。你知道吗

典型的元组如下所示:

(('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对象没有打印,取而代之的是15,同样在标题之后,下面的行没有正确对齐。你知道吗

输出:

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

Tags: noinformatdatetimetemplateregistration元组state
1条回答
网友
1楼 · 发布于 2024-10-03 02:32:06

使用一些较大的宽度,例如25,但也添加!s作为.format转换标志,以强制datetime转换为str

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        

相关问题 更多 >