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

时间:2013-02-27 00:39:37

标签: python postgresql basehttpserver

我使用BaseHttpServer设置了一个基本的python webserver,并且正在练习从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")

print语句用于调试控制台,它提供正确的输出:

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

我只是想尝试将某些列输出到网页,当我到达最后一行for row [2]时,我收到此错误:

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

我检查过,我数据库中的那些列的类型是interval。我如何像其他列的varchar一样迭代它们?

1 个答案:

答案 0 :(得分: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对象放在可以迭代的元组中。