[Tutor] Convert a 3letter month, is there a better way?

Lloyd Kvam pythontutor@venix.com
Fri Jun 13 10:29:01 2003


If you are using MySQL and the MySQLdb module, you should also be using
mx.DateTime.  A different approach would look like this:

import mx.DateTime as DT
thedate = DT.Parser.DateFromString(input_date)
cursor.execute("UPDATE mytable SET some_date_field=%s", thedate)

The MySQLdb module will handle putting a DT.Date variable into the proper
format for MySQL.  The %s is simply a place holder and not an EXACT duplicate
of the python format string specifier.  The python DB-API.2 spec is fairly
readable, though you will likely be checking some things against the module
source code.
http://www.python.org/peps/pep-0249.html
PEP 249 -- Python Database API Specification v2.0

I used the Python interactive window to verify that DateFromString can
handle your input format.
 >>> x = DT.Parser.DateFromString("06-JUN-03")
 >>> x
<DateTime object for '2003-06-06 00:00:00.00' at 13aa8d0>

DAVID BABCOCK wrote:
> I'm not at home to try this and even see if it works correctly. So be 
> kind if code wrong.
> 
> The Date comes in this format:  DD-MM-YY (ex. 12-JUN-03)
> So the list is ['12-JUN-03']
> 
> Converting the day and year is easy. But is there a better way to 
> convert the month to a number format like: JUN = 06
> 
> Here is my idea I haven't been able to test out yet.
> 
> def ConvertDate (date)
>     mlist = [JAN,FEB,....DEC]      mlist2 = ["01","02",..."12]  #needs 
> xx for mysql format.
>     sdate = date.split('-')      #break date into 3 parts
>     x=0
>     for x in range(11)
>         if sdate[1] == mlist[x]:
>               sdate[1] = mlist2[x]
>               break
> 
> Come to think about it, I think mysql will take the number 6 and put it 
> in as 06 when use the type date, so maybe having mlist2 would be 
> unnecessary. Might just be able to do: sdate[1] = x
> 
> But it does seem that I would need the mlist to convert to a number. Is 
> that true or is there a module to do it, that would result in less code?
> Thanks
> 
> _______________________________________________
> 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-443-6155
fax:	801-459-9582