364

How can I get the month name from the month number?

For instance, if I have 3, I want to return march

date.tm_month()

How to get the string march?

JMax
  • 26,109
  • 12
  • 69
  • 88
Rajeev
  • 44,985
  • 76
  • 186
  • 285

17 Answers17

573
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

Returns: December

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.

mydate.strftime("%b")

For the example above, it would return Dec.

JMax
  • 26,109
  • 12
  • 69
  • 88
  • 24
    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. calendar.month_name[i] or calendar.month_abbr[i] are more useful here. – Jay Sheth Apr 06 '16 at 17:27
  • 18
    `mydate.strftime("%b")` returns short notation for month name. (For the example above, it would return `Dec`) – GiriB Mar 07 '17 at 03:59
  • 9
    The OP want to use an integer as input, not a datetime.datetime object.You can use mydate = datetime.datetime(2019, integer , 1, 0, 0) but it's rather ugly – Rutger Hofste Jul 30 '19 at 10:31
  • 5
    I fail to see how this answers the question. – cglacet May 28 '20 at 17:55
  • What even is %b or %B ? – SherylHohman Jun 29 '20 at 20:19
  • 1
    @SherylHohman: this is plainly explained on the link in the doc and explicit in my answer: %B is Month as locale’s full name & %b is Month as locale’s abbreviated name – JMax Jun 30 '20 at 14:28
  • 1
    My bad. I misunderstood the %b and %B part of your answer. The actual issue, which distracted me, is that the OP wants to know how to turn a integer, 1 .. 12, into a month name. Instead you gave an Answer turning datetime.now() into a month name. The disconnect tripping up so many people is: what's the relation of datetime.now() to an integer 1..12? As is, this post doesn't include an Answer to the OP's question. OTOH, many landing here were looking for the Answer to a different Q, that you did answer, which is also valuable! Perhaps tying it in to, or adding A to OP's Q, would be beneficial? – SherylHohman Jun 30 '20 at 18:32
  • 4
    Note that %B may return month name in wrong case if non-english locale is used. For example for ru_RU locale %B returns "января" instead of "январь". – sikmir Sep 06 '20 at 15:26
  • 1
    @DeanChristianArmada why? It doesn't even answer the question... It answers the question *`Get the current month's name`*, not *`Get month name from number`* – Tomerikoo Nov 17 '20 at 12:47
  • 1
    @Tomerikoo True It did not answer the OP's question. It answered an entirely different question. He *should* *add* info relevant to OP's Q to this post, so it does address the Q, while keeping this info in place, because even more people arrive here looking for that. Because so many have accidentally landed here, trying to find an answer to that other Q, & it has so many upvotes, it won't be removed. But you are correct, the proper comment is "this should be the answer on a *different question*". Or an edit could answer both. – SherylHohman Nov 18 '20 at 23:29
  • @SherylHohman I agree. I guess many people got here because of the `Get month name...` part of the title and found this helpful, even though it doesn't answer the question ***on this page*** – Tomerikoo Nov 19 '20 at 07:38
  • This is nice and useful, but it is not an accurate answer to the question. ... calendar.month_name[3] would do – Javi May 13 '22 at 07:02
389

Calendar API

From that you can see that calendar.month_name[3] would return March, and the array index of 0 is the empty string, so there's no need to worry about zero-indexing either.

siame
  • 8,347
  • 3
  • 25
  • 26
  • 53
    You can also use calendar.month_abbr[i] for a short month name - e.g. Mar. – Jay Sheth Apr 06 '16 at 17:25
  • 9
    Note: you may need to `import calendar` at the top of your file before you can use it. – SherylHohman Jun 30 '20 at 18:41
  • 2
    If someone is looking to do this in pandas, solution is here: https://stackoverflow.com/questions/36010999/convert-pandas-datetime-month-to-string-representation. It's just that this is the first result that comes when looking for month name in string format question. Thought to put here in case. – Sulphur May 09 '21 at 23:17
  • @JaySheth's comment should be added to the accepted answer. – Tushar Vazirani Mar 29 '23 at 17:31
81
import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

April

Morwenn
  • 21,684
  • 12
  • 93
  • 152
Mike Yantis
  • 811
  • 6
  • 2
  • Interesting. I Like this perspective. It might be good to point out that for this use case, the year and the numeric day of the month (1..31) are irrelevant, & would not change the output of this function call. That is why they can be hard coded with arbitrary (but valid) values. Generally it's a good idea to highlight parts of your answer that specifically addresses OP's issue, & point out any caveats in using your code. Explanations increase long term value, promote spreading of knowledge, & increases likelihood of upvotes. Code-only answers are generally discouraged, to keep SO quality high – SherylHohman Jun 30 '20 at 19:19
  • Also, It'd be beneficial to include what `%B` stands for here, so future visitors can quickly understand how/why this function, and your code, works, and can immediately apply it to their own code. Explanations facilitate Rapid uptake of knowledge, providing a completely self-explanatory solution ;-). – SherylHohman Jun 30 '20 at 19:23
60

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.

calendar.month_name[i]

or

calendar.month_abbr[i]

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 ("")

Sample output:

January
Jan

February
Feb

March
Mar

...
Jay Sheth
  • 1,738
  • 16
  • 15
  • thank you for your answer. if i might add a suggestion, you could add some examples of input and outputs to show how to use this code and the difference between `month_name` and `month_abbr` – JMax May 03 '16 at 14:40
  • This is helpful, I suggest using `range(1, 13)` in your example so you get all 12 months in the output. – davejagoda Jun 19 '16 at 11:29
  • Good point. range(start, end) goes from start, up to, but not including end. Ie uses start ... end-1. – SherylHohman Jun 29 '20 at 20:16
26
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'
ancho
  • 1,060
  • 16
  • 24
20

To print all months at once:

 import datetime

 monthint = list(range(1,13))

 for X in monthint:
     month = datetime.date(1900, X , 1).strftime('%B')
     print(month)
Ivo Chula
  • 211
  • 2
  • 4
18

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])
Brett Rudder
  • 309
  • 2
  • 3
14

Some good answers already make use of calendar but the effect of setting the locale hasn't been mentioned yet.

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[1] == 'janvier'
assert calendar.month_abbr[1] == '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() […]

cglacet
  • 8,873
  • 4
  • 45
  • 60
  • 2
    Good addition, just I suggest to add a fallback culture or just wrap the setLocale call in a try/except, because if that culture is not available you get an exception (happened just to me after trying this ;)) – firepol Jun 09 '20 at 16:40
  • 1
    I think I'll leave the code as is because setting the locale is probably not something you would do anyway near that code. I just wanted to highlight how setting the locale also impact the values from `calendar`. I can maybe update the text. – cglacet Jun 10 '20 at 09:06
13

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)

It Outputs:

>>> September

(This Was The Real Date When I Wrote This)

Random Person
  • 399
  • 1
  • 3
  • 9
13

datetime — Basic date and time types — Python documentation

A list of all the strftime format codes. Names of months and nice stuff like formatting left zero fill. Read the full page for stuff like rules for "naive" arguments. Here is the list in brief:

%a  Sun, Mon, …, Sat 
%A  Sunday, Monday, …, Saturday 
%w  Weekday as number, where 0 is Sunday 
%d  Day of the month 01, 02, …, 31
%b  Jan, Feb, …, Dec
%B  January, February, …, December
%m  Month number as a zero-padded 01, 02, …, 12
%y  2 digit year zero-padded 00, 01, …, 99
%Y  4 digit Year 1970, 1988, 2001, 2013
%H  Hour (24-hour clock) zero-padded 00, 01, …, 23
%I  Hour (12-hour clock) zero-padded 01, 02, …, 12
%p  AM or PM.
%M  Minute zero-padded 00, 01, …, 59
%S  Second zero-padded 00, 01, …, 59
%f  Microsecond zero-padded 000000, 000001, …, 999999
%z  UTC offset in the form +HHMM or -HHMM   +0000, -0400, +1030
%Z  Time zone name  UTC, EST, CST
%j  Day of the year zero-padded 001, 002, …, 366
%U  Week number of the year zero padded, Days before the first Sunday are week 0
%W  Week number of the year (Monday as first day)
%c  Locale’s date and time representation. Tue Aug 16 21:30:00 1988
%x  Locale’s date representation. 08/16/1988 (en_US)
%X  Locale’s time representation. 21:30:00 
%%  literal '%' character.
ojdo
  • 8,280
  • 5
  • 37
  • 60
dhm
  • 157
  • 1
  • 2
6

'01' to 'Jan'

from datetime import datetime

datetime.strptime('01', "%m").strftime("%b")    
chaim glancz
  • 71
  • 1
  • 2
2

For arbitaray range of month numbers

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.

Mehtab Pathan
  • 443
  • 4
  • 15
2

instead of import or downloading a new lib, you can use my manual function:

copy the code to a new .py file and run it

quick explanation:

change your_number and print month_from_number, you will get the month

    your_number = 10

    def num_to_month(*args, **kwargs):

        num = kwargs.get("num", None)

        if int(num) <= 12 and int(num) > 0:

            list_of_months = {'1': 'January', '2': 'February', '3': 'March',
                              '4': 'April', '5': 'May', '6': 'June', '7': 'July',
                              '8': 'August', '9': 'September', '10': 'October',
                              '11': 'November', '12': 'December'}

            return list_of_months[num]

        else:

            print('num_to_month function error: "num=' + str(num) + '"')

    month_from_num = num_to_month(num=your_number)

    print(month_from_num)

the result will be October

Kamal Zaitar
  • 101
  • 1
  • 3
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – blazej Aug 20 '21 at 16:56
1

This script is to show how to get calendar month abbreviations for a month variable/column in a data frame. Note that the assumption is that the values of the month column/variable are all numbers and maybe there might be some missing values.

# Import the calendar module
  import calendar
    
# Extract month as a number from the date column
  df['Month']=pd.DatetimeIndex(df['Date']).month

# Using list comprehension extract month abbreviations for each month number
 df['Month_abbr']=[calendar.month_abbr[int(i)] if pd.notna(i) else i for i in df['Month']]
Jane Kathambi
  • 695
  • 6
  • 8
1

If you just have the month number and not a datetime instance you could built a small function to map number with label as this:

def monthname(m):
    d={1:'En',2:'Fe',3:'Mr',4:'Ab',5:'My',6:'Jn',7:'Jl',8:'Ag',9:'Se',10:'Oc',11:'No',12:'Di'}
    return d[m]
Salva.
  • 99
  • 1
  • 1
  • 8
0

Came here from a related SO question about generating a list of month names.

Many of the options on that question, as this one, suggested the calendar module, though the same is possible with a datetime list comprehension:

month_names = [dt.datetime.strptime(str(n), '%m').strftime('%B') for n in range(1, 13)]

Should you be approaching this question from the perspective of looking up month names for a large number of integers, indexing a pre-generated list may have efficiency benefits.

kowpow
  • 95
  • 2
  • 8
-8

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December
jdvcal
  • 37
  • 1
  • 7
  • 4
    As shown in the other answers, this functionality already exists in the built-in `calendar` module. What benefit might there be to creating your own function to replicate the same results? Also, a dictionary would be much faster than a series of elif statements. – Tom Aug 10 '17 at 22:34
  • 5
    Apart from all other issues, your function works only for english locale – mick88 Oct 23 '18 at 14:29