How to initialize a table of months.

7stud bbxx789_05ss at yahoo.com
Sun Apr 15 23:30:57 EDT 2007


On Apr 15, 7:30 pm, "Steven W. Orr" <ste... at syslang.net> wrote:
> I'm reading a logfile with a timestamp at the begging of each line, e.g.,
>
> Mar 29 08:29:00
>
> I want to call datetime.datetim() whose arg2 is a number between 1-12 so I
> have to convert the month to an integer.
> I wrote this, but I have a sneaky suspicion there's a better way to do it.
>
> mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6,
>          'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 }
>
> def mon2int( mon ):
>      global mons
>      return mons[mon]
>
> Is there a generator expression or a list comprehension thingy that would
> be *betterer*? (I realize it's probably not that important but I find lots
> of value in learning all the idioms.)
>
> TIA
>
> --
> Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
> happened but none stranger than this. Does your driver's license say Organ ..0
> Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
> individuals! What if this weren't a hypothetical question?
> steveo at syslang.net

Just in case you're still interested(despite not needing to per John
Zenger's solution), you could do this:

import calendar

months = calendar.month_abbr  #returns an array with the 0 element
empty
                              #so the month names correspond to
indexes 1-12
d = {}
for i in range(1, 13):
    d[months[i]] = i

print d





More information about the Python-list mailing list