Get month name from number

PythonDatetimeDate

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

http://docs.python.org/library/calendar.html#calendar.month_name">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.

Solution 3 - Python

import datetime

monthinteger = 4

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

print month

>April

Solution 4 - Python

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

...

Solution 5 - Python

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'

Solution 6 - Python

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)

Solution 7 - Python

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])

Solution 8 - Python

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

Solution 9 - Python

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)

Solution 10 - Python

8.1. datetime — Basic date and time types — Python 2.7.17 documentation https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

A list of all the strftime arguments. 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.

Solution 11 - Python

'01' to 'Jan'

from datetime import datetime

datetime.strptime('01', "%m").strftime("%b")    

Solution 12 - Python

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.

Solution 13 - Python

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']]

Solution 14 - Python

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=str(your_number))

    print(month_from_number)

the result will be October

Solution 15 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajeevView Question on Stackoverflow
Solution 1 - PythonJMaxView Answer on Stackoverflow
Solution 2 - PythonsiameView Answer on Stackoverflow
Solution 3 - PythonMike YantisView Answer on Stackoverflow
Solution 4 - PythonJay ShethView Answer on Stackoverflow
Solution 5 - PythonanchoView Answer on Stackoverflow
Solution 6 - PythonIvo ChulaView Answer on Stackoverflow
Solution 7 - PythonBrett RudderView Answer on Stackoverflow
Solution 8 - PythoncglacetView Answer on Stackoverflow
Solution 9 - PythonRandom PersonView Answer on Stackoverflow
Solution 10 - PythondhmView Answer on Stackoverflow
Solution 11 - Pythonchaim glanczView Answer on Stackoverflow
Solution 12 - PythonMehtab PathanView Answer on Stackoverflow
Solution 13 - PythonJane KathambiView Answer on Stackoverflow
Solution 14 - PythonKamal ZaitarView Answer on Stackoverflow
Solution 15 - PythonjdvcalView Answer on Stackoverflow