views:

72

answers:

4

Hello all,

I am looking to do something really simple. Merely convert a string, such as 'december' into something I can use with MySQL (such as '12').

At the moment I use a dict,

month_map = {
    'december': '12',
    'november': '11',
    'october': '10',
    'september': '09',
    'august': '08',
    'july': '07',
    'june': '06',
    'may': '05',
    'april': '04',
    'march': '03',
    'february': '02',
    'january': '01'
}

and then month_map.get('december').

Does any function already exist within the standard python modules that can achieve this? Apologies if this has already been asked.. the questions I have found using search seem a little different.

+1  A: 

Python dateutil

Sjoerd
+2  A: 

It's locale-dependent, but you can accomplish this with strptime:

>>> import datetime
>>> datetime.datetime.strptime('december', '%B').month
12
>>> datetime.datetime.strptime('january', '%B').month
1
Mark Rushakoff
Thanks. Exactly what I was looking for.
kahrn
@kahrn: then select this answer by clicking on the checkmark below the answer's votes.
ΤΖΩΤΖΙΟΥ
+1  A: 

One thing you could do is:

>>> datetime.datetime.strptime('december', '%B').month
12

'%B' would match full locale name of the month.

SilentGhost
+1  A: 

In a database you usually have lookup tables mapping the strings to their key values (usually ints, sometimes GUIDs). For months this might not be a big deal because everyone knows what month 5 is, but if you start doing translation in the client side for more odd things, like, say, mapping states to ints then you're doing something wrong.

To be strictly correct, the DB should have this map in a lookup table, and then you should use that to do the translations.

Donnie
Thanks. I will keep this in mind.
kahrn