How can I get the month name from the month number?
For instance, if I have
3, I want to return
How to get the string
From that you can see that
calendar.month_name would return
March, and the array index of
0 is the empty string, so there’s no need to worry about zero-indexing either.
import datetime mydate = datetime.datetime.now() mydate.strftime("%B")
Some more info on the Python doc website
[EDIT : great comment from @GiriB] You can also use
%b which returns the short notation for month name.
For the example above, it would return
import datetime monthinteger = 4 month = datetime.date(1900, monthinteger, 1).strftime('%B') print month
This is not so helpful if you need to just know the month name for a given number (1 – 12), as the current day doesn’t matter.
are more useful here.
Here is an example:
import calendar for month_idx in range(1, 13): print (calendar.month_name[month_idx]) print (calendar.month_abbr[month_idx]) print ("")
January Jan February Feb March Mar ...
import datetime mydate = datetime.datetime.now() mydate.strftime("%B") # 'December' mydate.strftime("%b") # 'dec'
I’ll offer this in case (like me) you have a column of month numbers in a dataframe:
df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])
This Is What I Would Do:
from datetime import * months = ["Unknown", "January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] now = (datetime.now()) year = (now.year) month = (months[now.month]) print(month)
(This Was The Real Date When I Wrote This)
Calendar set month names according to the current locale, for exemple in French:
import locale import calendar locale.setlocale(locale.LC_ALL, 'fr_FR') assert calendar.month_name == 'janvier' assert calendar.month_abbr == 'jan'
If you plan on using
setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]
Extension modules should never call setlocale() […]