Struggling to convert a mysql datetime object to a python string of a different format
Tim Chase
python.list at tim.thechases.com
Thu Aug 5 15:09:52 EDT 2010
On 08/05/10 13:52, Νίκος wrote:
> dataset = cursor.fetchall()
>
> for row in dataset:
> print ( '''<tr> ''' )
>
> date = row[2].strftime( '%d %b, %H:%M' )
>
> print ( '''<td> %s</td> <td> %s</td> <td> %s</td> ''' %
> ( row[0], row[1], date ) )
>
> Unfortunately had to ditch the 'for entry in row' line because
> couldn't iterate over the items of the row.
>
> Could you please shoe me how could i do the same thing with
> iteration?!
Well, depending on whether "row" is a tuple or a list, you can do
either
row[2] = row[2].strftime(...) # if it's a list
# the assignment will fail if it's a tuple
or you can just iterate over a predefined list/tuple:
for row in dataset:
print ("<tr>")
for item in (row[0], row[1], row[2].strftime(...)):
print ("<td>%s</td" % item)
print ("</tr>")
Though I think I'd make it a bit clearer by naming the fields:
for host, hits, dt in dataset:
print ("<tr>")
for item in (host, hits, dt.strftime(...)):
print ("<td>%s</td>" % item)
print ("</tr>")
Or perhaps even just
print ("".join("<td>%s</td>" % item
for item in (host, hits, dt.strftime(...))
)
Whichever you prefer. I think I'm partial to the 2nd-from-last
version, especially as the list of fields may grow.
-tkc
More information about the Python-list
mailing list