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

Alfred Milgrom fredm@smartypantsco.com
Fri Jun 13 02:19:02 2003


Using a dictionary seems like a better for what you are trying to do:

 >>> sdate=[12,'JUN',3]
 >>> months={'JAN':1, 'FEB':2, 'MAR':3, 'APR':4, 'MAY':5, 'JUN':6, 'JUL':7, 
'AUG':8, 'SEP':9, 'OCT':10, 'NOV':11, 'DEC':12}
 >>> if sdate[1] in months:
         sdate[1] = months[sdate[1]]
else:
         print 'data error'


 >>> sdate
[12, 6, 3]

Note that my code sample has an error trap in case the data comes in a 
format other than what you are expecting.
If you are 100% sure that the data will be a 3letter month abbreviation in 
caps, then you can omit the error message part and simplify it to
 >>> sdate[1] = months[sdate[1]]

HTH
Fred Milgrom


At 01:51 AM 13/06/03 -0400, 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
>