MySQLdb and DateTime objects

Nick Arnett narnett at mccmedia.com
Fri Apr 26 16:06:55 EDT 2002


I'm have a bit of trouble figuring out how to use a date field retrieved
from MySQL when updating a record in another table.  Rather than a date
string, MySQLdb returns a DateTime object.  At first, imagining that since
it came out of a field, the date object would also then match the field in a
subsequent operation.  But no, it doesn't -- it produces an error.

E.g., "SELECT DISTINCT(Date) FROM Foo" returns a list of tuples whose first
member is a DateTime object, not a date string.  If the dates are in a list
called myDates, and I do something like, "UPDATE Foo SET X=%s WHERE Date=%s"
I get an error, as MySQLdb tries to insert a reference to the DateTime
object, rather than a date string.

What seemed to be the obvious solution was to use
MySQLdb.times.format_TIMESTAMP() or MySQLdb.times.format_DATE()-- but that
doesn't work, it returns an error:

  File "C:\Python22\Lib\site-packages\MySQLdb\times.py", lin
STAMP
    return d.strftime("%Y-%m-%d %H:%M:%S")
AttributeError: 'tuple' object has no attribute 'strftime'

Nor does str(), but that seemed like a long shot, anyway.

How the heck do I get this object back into a form that will work in a
query?

And is it just me, or is it rather inelegant that MySQLdb converts
timestamps into a DateTime object on the way out, but doesn't do the
reverse?

Thanks in advance.

Nick

--
narnett at mccmedia.com
(408) 904-7198






More information about the Python-list mailing list