Figure out month number from month abbrievation

Fredrik Lundh fredrik at pythonware.com
Wed Apr 12 16:41:49 EDT 2006


"Bill" wrote:

> I'm parsing the output of the finger command, and was wondering
> something...If I'm given a month abbrievation (such as "Jan"), what's
> the best way to figure out the month number?  I see that there's
> something called "month_abbr" in the calendar module.  However, when I
> try to do calendar.month_abbr.index("Jan"), I get "_localized_month
> instance has no attribute 'index'."  So it seems that month_abbr isn't
> a regular list.  I'm currently doing it this way:
>
> def month_number(monthabbr):
>     """Return the month number for monthabbr; e.g. "Jan" -> 1."""
>     for index, day in enumerate(calendar.month_abbr):
>         if day == monthabbr:
>             return index
>
> which works well enough but isn't very clever.  I'm pretty new to
> Python; what am I missing here?

a couple of things, I think.

... first, you can use list(seq) to convert any sequence to a list object,
so you could do

    return list(calendar.month_abbr).index(monthabbr)

if you prefer to do things in one line.


... but it also looks as if the meaning of the word "localized" isn't clear to
you; if you changed the locale, those names will be translated:

>>> list(calendar.month_abbr)
['', 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec']

which will cause your finger program to break...

... and I'm quite sure that you could have written down the abbreviations
in far less time than it took you to compose that mail ;-)

    MONTHS = ['',
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ]

    month_number = MONTHS.index

</F>






More information about the Python-list mailing list