How to initialize a table of months.

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Mon Apr 16 01:19:30 EDT 2007


In article <mailman.6565.1176687041.32031.python-list at python.org>,
 "Steven W. Orr" <steveo 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.)

There's no harm in your method as written, though it were probably wise 
to tolerate variations in capitalization.  But if you want to be cute 
about it, you could write something like this to set up your table:

  from datetime import date

  months = dict((date(1900, x+1, 1).strftime('%b').lower(), x+1) 
                for x in xrange(12))

  def month2int(mName):
    return months[mName.lower()]

If you don't like the lookup table, you can get a nicely portable result 
without it by using time.strptime(), e.g.,

  import time

  def month2int(mName):
    return time.strptime(mName, '%b').tm_mon  # parses "short" names

Without knowing anything further about your needs, I would probably 
suggest the latter simply because it makes the hard work be somebody 
else's problem.

Cheers,
-M

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list