In Python, you can use the calendar module’s calendar.month_name[number]
attribute to get the month name from a given number.
For example, month_name = calendar.month_name[6]
will give you June as an output. If you have a datetime object, datetime(2022, 10, 12, 18, 45, 56)
, then it will return October as a month name.
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.
Table of contents
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.
- 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.
- Use calendar.month_name data attribute
Use the
calendar.month_name[number]
attribute to get the month’s full name from a number.
Thecalendar.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 andcalendar.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.
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])
Output:
Month Number: 2 Month full name is: February
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 Abbreviated Month Name from Number in Python
If you want to convert the 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.
To get the abbreviated month name from a number, you can use the following code:
import calendar
month_number = 2
print('Month Number:', month_number)
print('Month short name is:', calendar.month_abbr[month_number])
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 represents 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 must use the two directives below.
%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
Leave a Reply