PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python Get Month Name From Number

Python Get Month Name From Number

Updated on: October 13, 2022 | Leave a Comment

In this lesson, you’ll learn how to:

  • Get the month name from a month number. i.e., convert the month number to the month’s full name (like December) and short name (like Dec).
  • Get the month’s name from a date.
  • Convert month name to month number and vice versa

For example:

  • If the number is 6, it should return June as an output.
  • If you have a datetime object like, datetime(2022, 10, 12, 18, 45, 56), then it should return October as a month name.

Table of contents

  • How to Get Month Name from Number in Python
    • Example: Get Month Name from Number in Python
  • Get Month Name from Datetime in Python
    • Get Month Name from Datetime using strftime()
  • Convert Month Name to Month Number in Python
  • Convert Month Number to Month name in pandas
    • Convert pandas datetime to month name
    • Convert a column of month numbers in a dataframe to a month name

How to Get Month Name from Number in Python

We can use two ways to get the month name from a number in Python. The first is the calendar module, and the second is the strftime() method of a datetime module. The below steps show how to get the month name from a number in Python using the calendar module.

  1. Import calendar module

    Calendar is a built-in module available in Python. This module allows you to output calendars like the Unix cal program and provides additional useful functions related to the calendar.

  2. Use calendar.month_name data attribute

    Use the calendar.month_name[number] attribute to get the month’s full name from a number.

    The calendar.month_name[num] is an array that represents the months of the year in the current locale. This follows the standard convention of January being month number 1, so it has a length of 13 and calendar.month_name[0] is the empty string.

    For example, calendar.month_name[2] will return February as a month name. Here 2 is the month number.

  3. Use calendar.month_abbr data attribute

    If you want to convert month number to an abbreviated month name, then use the calendar.month_abbr data attribute.

    For example, calendar.month_abbr[2] will return Feb as a month name. Note: Feb is the short name of February month.

Example: Get Month Name from Number in Python

import calendar

num = 2
print('Month Number:', num)

# get month name
print('Month full name is:', calendar.month_name[num])
print('Month short name is:', calendar.month_abbr[num])

Output:

Month Number: 2
Month full name is: February
Month short name is: Feb

Also, you can get all month’s names using this data attribute.

Example:

import calendar

# get all months name using number
for i in range(1, 13):
    # get month name
    print('Month full name is:', calendar.month_name[i])
    print('Month short name is:', calendar.month_abbr[i])

Get Month Name from Datetime in Python

Use the below code to get the month name from a datetime object.

  • First, extract the month number from a datetime object using the month attribute.
  • Next, use the calendar.month_name[num] attribute to get the month name.

Example:

from datetime import datetime
import calendar

dob = datetime(1994, 8, 24)
print('DateTime:', dob)

# get month number
num = dob.month
print('Month Number:', num)

# get month name
print('Month full name is:', calendar.month_name[num])
print('Month short name is:', calendar.month_abbr[num])

Output:

DateTime: 1994-08-24 00:00:00
Month Number: 8
Month full name is: August
Month short name is: Aug

Get Month Name from Datetime using strftime()

The strftime() method represent datetime in string formats. Use the datetime.strftime(format) to convert a datetime object into a string as per the corresponding format.

The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

In our case, we need the month name, so we need to use the below two directives.

  • %B: Returns the full name of the month. Like, June, March
  • %b: Returns the short name of the month (First three characters). Like, Mar, Jun

See more directives for reference.

Example:

from datetime import datetime

# get today's datetime
now = datetime.now()
print('DateTime:', now)

print('Month Number:', now.month)
print('Month full name:', now.strftime('%B'))
print('Month short name:', now.strftime('%b'))

Output:

DateTime: 2022-10-12 15:18:09.688342
Month Number: 10
Month full name: October
Month short name: Oct

Convert Month Name to Month Number in Python

Now, let’s see how to convert a month name to a month number. We will also see how to convert a month number to an abbreviated month name or an abbreviated month name to a month number.

Example:

Using this example, you can map the month name to the month number and vice versa.

import calendar
from datetime import datetime

dob = datetime(1994, 8, 24)
print('DateTime:', dob)

# get month number
num = dob.month
print('Month Number:', num)

# month number to month name
fn = calendar.month_name[num]
print('Month full name is:', fn)

sn = calendar.month_abbr[num]
print('Abbreviated month name is:', sn)

# convert month name to number
# Get month number from full month name
f_mn = list(calendar.month_name).index(fn)
print('Month Number:', f_mn)

# Get month number from abbreviated month name
s_mn = list(calendar.month_abbr).index(sn)
print('Month Number:', s_mn)

Output:

DateTime: 1994-08-24 00:00:00
Month Number: 8

Month full name is: August
Abbreviated month name is: Aug

Month Number: 8
Month Number: 8

Convert Month Number to Month name in pandas

If you are working with a pandas dataframe or series, these examples will help you. First, let’s see how to get the month name of a pandas series of multiple dates.

Use the dt.month_name() function to get the month name in pandas.

Convert pandas datetime to month name

Example:

import pandas as pd

# Create a Series
dates = pd.Series(['2022-1-30', '2022-4-18', '2022-7-23'])

# Create index
idx = [dates[0], dates[1], dates[2]]

# set the index
dates.index = idx

dates = pd.to_datetime(dates)
print('All Dates')
print(dates)

# Get month name
print('Month name')
result = dates.dt.month_name(locale='English')
print(result)

Output:

All Dates
2022-1-30   2022-01-30
2022-4-18   2022-04-18
2022-7-23   2022-07-23
dtype: datetime64[ns]

Month name
2022-1-30    January
2022-4-18      April
2022-7-23       July
dtype: object

Convert a column of month numbers in a dataframe to a month name

If one of the columns of a pandas dataframe contains a month number, then use the below code to convert the month number to the month name.

Example:

import pandas as pd
import calendar

# Create dict object
student_dict = {"name": ["Joe", "Nat", "Harry"], "join_month": [8, 4, 11]}
# Create DataFrame from dict
df = pd.DataFrame(student_dict)
print('Student Details')
print(df)

# get months name
month_names = df['join_month'].apply(lambda x: calendar.month_name[x])
print('Months Name')
print(month_names)

# replace column join_month
df['join_month'] = month_names
print('Student Details')
print(df)

Output:

Student Details
    name  join_month
0    Joe           8
1    Nat           4
2  Harry          11

Months Name
0      August
1       April
2    November
Name: join_month, dtype: object

Student Details
    name join_month
0    Joe     August
1    Nat      April
2  Harry   November

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com