Get month name from number
Asked Answered
G

18

380

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?

Goa answered 2/7, 2011 at 14:17 Comment(0)
S
398

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.

Straggle answered 2/7, 2011 at 14:21 Comment(4)
You can also use calendar.month_abbr[i] for a short month name - e.g. Mar.Medamedal
Note: you may need to import calendar at the top of your file before you can use it.Cattalo
If someone is looking to do this in pandas, solution is here: #36011499. 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.Palladino
@JaySheth's comment should be added to the accepted answer.Congenital
L
583
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.

Lycaon answered 2/7, 2011 at 14:21 Comment(12)
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.Medamedal
mydate.strftime("%b") returns short notation for month name. (For the example above, it would return Dec)Brunildabruning
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 uglyWinny
I fail to see how this answers the question.Misdeed
What even is %b or %B ?Cattalo
@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 nameLycaon
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?Cattalo
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 "январь".Cultivator
@DeanChristianArmada why? It doesn't even answer the question... It answers the question Get the current month's name, not Get month name from numberChanukah
@Chanukah 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.Cattalo
@Cattalo 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 pageChanukah
This is nice and useful, but it is not an accurate answer to the question. ... calendar.month_name[3] would doDeduce
S
398

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.

Straggle answered 2/7, 2011 at 14:21 Comment(4)
You can also use calendar.month_abbr[i] for a short month name - e.g. Mar.Medamedal
Note: you may need to import calendar at the top of your file before you can use it.Cattalo
If someone is looking to do this in pandas, solution is here: #36011499. 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.Palladino
@JaySheth's comment should be added to the accepted answer.Congenital
L
83
import datetime

monthinteger = 4

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

print (month)

April

Linettelineup answered 11/2, 2015 at 4:6 Comment(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 highCattalo
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 ;-).Cattalo
M
64

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

...
Medamedal answered 12/4, 2016 at 15:19 Comment(3)
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_abbrLycaon
This is helpful, I suggest using range(1, 13) in your example so you get all 12 months in the output.Decelerate
Good point. range(start, end) goes from start, up to, but not including end. Ie uses start ... end-1.Cattalo
S
26
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'
Socage answered 7/1, 2015 at 11:26 Comment(0)
P
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)
Pandit answered 4/8, 2020 at 14:53 Comment(0)
P
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])
Provenance answered 21/3, 2016 at 19:53 Comment(1)
This is a great answer and will likely be required most of the time.Dubois
D
15

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.
Dipole answered 28/1, 2020 at 15:17 Comment(0)
M
15

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() […]

Misdeed answered 28/5, 2020 at 18:14 Comment(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 ;))Saxtuba
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.Misdeed
N
14

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)

Nitrous answered 30/9, 2016 at 16:48 Comment(0)
B
6

'01' to 'Jan'

from datetime import datetime

datetime.strptime('01', "%m").strftime("%b")    
Brezhnev answered 22/2, 2022 at 19:18 Comment(0)
E
3

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

Excrescency answered 15/8, 2021 at 11:40 Comment(1)
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.Politburo
K
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.

Kyles answered 15/8, 2018 at 10:24 Comment(0)
N
2

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']]
Nonreturnable answered 3/6, 2021 at 16:23 Comment(2)
It would be nice to add a description of how your code works; this will help visitors even moreGarneau
@Garneau thank you for the suggestion, I have now added the descriptions.Nonreturnable
M
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]
Miriam answered 18/7, 2022 at 10:41 Comment(0)
L
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.

Livingstone answered 5/10, 2022 at 11:37 Comment(0)
I
0
import datetime as dt

df['month_name'] = df['month'].dt.month_name()

this might be helpful as well.

if you want to last three letter.

df['month_name'] = df['month'].dt.month_name().str.slice(stop= 3)
Indefinite answered 5/10, 2023 at 18:1 Comment(0)
H
-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
Herbert answered 9/5, 2017 at 13:34 Comment(2)
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.Yammer
Apart from all other issues, your function works only for english localeMccormick

© 2022 - 2024 — McMap. All rights reserved.