On Wed, 2006-04-05 at 10:50 -0400, Kent Johnson wrote: > Ray Allen wrote: > > I would like Python to convert a date returned by MySQL (2006-04-05)
Kent's advice below is of course correct, but I'd bet your variable is already a datetime.date (or mx.DateTime.Date with older Python releases). In that case you'd already be at step 7. When executing your update statement use the args field. cursor.execute("UPDATE table SET mydate=%s WHERE id=%s", (date_variable, recordID)) You should not have to worry about getting your date into the proper string format for the database SQL syntax. Here's the help from MySQLdb: help(curs.execute) execute(self, query, args=None) method of MySQLdb.cursors.Cursor instance Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any > to a > > user readable format such as 05-Apr-2006 for display and then to convert it > > back to ISO format for update. > > Here's one way: > > In [1]: from datetime import date > > In [2]: data = '2006-04-05' > > Use split() and int() to convert to a list of year, month, day > In [4]: ymd = map(int, data.split('-')) > > In [5]: ymd > Out[5]: [2006, 4, 5] > > Turn it into a date. The * makes the list act like individual parameters. > In [6]: d=date(*ymd) > > In [7]: d > Out[7]: datetime.date(2006, 4, 5) > > See the docs for the time module for info about strftime() format codes > In [8]: d.strftime('%d-%b-%Y') > Out[8]: '05-Apr-2006' > > ISO format is built-in. > In [9]: d.isoformat() > Out[9]: '2006-04-05' > > > For other input formats you might have to use time.strptime() to convert > to a time tuple, then pass the first three elements do date(): > > In [10]: import time > > In [15]: t=time.strptime(data, '%Y-%m-%d') > > In [16]: t > Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1) > > In [17]: date(*t[:3]) > Out[17]: datetime.date(2006, 4, 5) > > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 -- Lloyd Kvam Venix Corp _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor