TypeError: 'datetime.timedelta'对象不可迭代 - BaseHttpServer 问题

0 投票
1 回答
4202 浏览
提问于 2025-04-17 17:15

我搭建了一个简单的Python网页服务器,使用的是BaseHttpServer,并且正在练习从PostgreSQL数据库查询数据。一切进展顺利,但在解析SQL结果时遇到了一个错误。

这是我的代码:

cur=con.cursor()
cur.execute(('select * from stop_times as a, stop_times as b where a.train_id=b.train_id and a.station_name = %s and b.station_name= %s and a.arrival_time < b.arrival_time'), (origin_name, dest_name))

self.wfile.write("Train Number &nbsp &nbsp  Starting Station &nbsp &nbsp  Destination Station &nbsp &nbsp Departure Time &nbsp &nbsp Arrival Time <br />")

while True:
    row=cur.fetchone()
    if row==None:
        break

    print row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    for item in row[0]:
        self.wfile.write("%s"% item)
    self.wfile.write(" &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp")
    for item in row[3]:
        self.wfile.write("%s"% item)
    self.wfile.write(" &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp")

    for item in row[8]:                         
        self.wfile.write("%s"% item)
    self.wfile.write("&nbsp &nbsp &nbsp &nbsp")

    for item in row[2]:
        self.wfile.write("%s"% item)
    self.wfile.write("&nbsp &nbsp")

这个打印语句是用来调试的,输出到控制台,结果是正确的:

427 10:23:00 10:23:00 San Antonio 6 427 11:08:00 11:08:00 Millbrae
429 11:23:00 11:23:00 San Antonio 6 429 12:08:00 12:08:00 Millbrae
431 12:23:00 12:23:00 San Antonio 6 431 13:08:00 13:08:00 Millbrae

我只是想把某些列输出到网页上,但当我到达最后一个循环,处理row[2]时,就出现了这个错误:

File "./caltrainServer.py", line 129, in performQuery
for item in row[2]:
TypeError: 'datetime.timedelta' object is not iterable

我检查过了,数据库中的那些列是interval类型的。我该如何像处理其他varchar类型的列那样遍历它们呢?

1 个回答

2

你在不必要地遍历行值的内容。像这样的代码:

for item in row[0]:
    self.wfile.write("%s"% item)

可能可以改成:

self.wlfile.write(row[0])

当你用 row[x] 访问一个字符串时,其实是在逐个字母地遍历并写出每个字母。但是 row[2] 是一个 datetime.datetime 对象。由于 datetime.datetime 对象不能被遍历,所以你会看到那个错误信息。

你可以试试这样的写法:

self.wlfile.write((row[2]))

这样可以把 datetime 对象放进一个元组里,这样就可以遍历了。

撰写回答