How to get a Month Name in Python
Here’s the shortest method I could come up with:
>>> named_month = lambda month_num:datetime.date(1900,month_num,1).strftime('%B')
>>> print named_month(5)
'May'
How to get a Month Name in PythonHere’s the shortest method I could come up with:
5 Responses to “How to get a Month Name in Python” |
Here’s a 12-character-shorter version that I feel is nicer.
named_month = lambda month_num:calendar.month_name[month_num]Obviously requiring
import calendarbeforehand, as yours requiresimport datetime.This didn’t occur to me as instantly, but if we were golfing a usable function, it would probably be shortest to do:
named_month = calendar.month_name.__getitem__… which works the same (slightly more efficient, actually) and knocks off a further 16 characters. It is probably less readable, though. Actually, those 16 characters is the same amount we’d save if we used a single-character identifier for the index (which we obviously don’t want to do for readability reasons, so it’s probably not really a noteworthy saving at all.
If you don’t mind that it isn’t a function why not?
from calendar import month_name
But since calendar is in the stdlib I encourage you to use calendar.month_name[] every time except in CPU bound loops.
@Jeremy
Are you sure that would work if the calendar module were reimplemented in C?
@Rob
I’m not confident, but I don’t see why not. It’s a public data attribute of the module, so it would be available, and
.__getitem__should still work on it regardless of if it’s implemented in C or Python (it works for builtins written in C, such as lists).I don’t think it’s a good approach, since using special methods directly should be avoided if possible, but as far as I know it should work.