Question

I set up a basic python webserver using BaseHttpServer and am practicing querying data from a postgresql database. Everything is going swimmingly, but I have an error when I'm parsing the SQL results. Here is my code:

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")

The print statement is there for debugging to the console, and it gives the correct output:

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

I'm just trying to output certain columns to the web page, and when I get to that last for loop for row[2] I get this error:

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

I checked, and those columns in my database are of type interval. How do I iterate through them like I did with my other columns, which were of type varchar?

Was it helpful?

Solution

You are unnecessarily iterating over the contents of the row values. Lines like this:

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

Could likely be changed to

self.wlfile.write(row[0])

What you are doing, when row[x] is a string is actually iterating over each letter and writing it. But row[2] is a datetime.datetime object. And since datetime.datetime objects are not iterable, you get that error message.

Try instead something like:

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

That places the datetime object in a tuple which can be iterated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top