How to Convert Month Name to Number in Python?

In this tutorial, I will explain how to convert a month name to a number in Python. As a Python developer, I faced a real-time issue where I needed to convert a month name to a number in Python. I will explain various methods to achieve this task.

Methods to Convert Month Name to Number in Python

Python provides several ways to convert month names to numbers. We will explore different methods using built-in libraries and custom functions. Let’s get into each method with examples.

Read How to Validate Email Addresses in Python?

1. Use the datetime Module in Python

The datetime module in Python is a powerful tool for handling date and time. It includes a method called strptime which can parse a string representing a date and return a corresponding datetime object. Here’s how you can use it to convert a month name to a number:

from datetime import datetime

def month_name_to_number(month_name):
    date_object = datetime.strptime(month_name, '%B')
    return date_object.month

# Example usage
month_name = "November"
month_number = month_name_to_number(month_name)
print(f"The month number for {month_name} is {month_number}.")

Output:

The number of months between 2023-01-15 and 2024-11-13 is 22 months, accounting for partial months.

I have executed the above example code and added the screenshot below.

Convert Month Name to Number in Python

In this example, the strptime method takes a string and a format code. %B is the format code for the full month name. This method will convert “November” to the month number 11.

Check out How to Use the round() Function in Python?

2. Use a Dictionary for Conversion

Another simple method is to use a dictionary to map month names to their corresponding numbers. This approach is particularly useful if you need to handle both full month names and their abbreviations.

def month_name_to_number(month_name):
    month_dict = {
        "January": 1, "February": 2, "March": 3, "April": 4,
        "May": 5, "June": 6, "July": 7, "August": 8,
        "September": 9, "October": 10, "November": 11, "December": 12,
        "Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4,
        "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12
    }
    return month_dict.get(month_name, "Invalid month name")

# Example usage
month_name = "Nov"
month_number = month_name_to_number(month_name)
print(f"The month number for {month_name} is {month_number}.")

Output:

The month number for Nov is 11.

I have executed the above example code and added the screenshot below.

How to Convert Month Name to Number in Python

In this example, we use a dictionary to map both full month names and their three-letter abbreviations to their numeric equivalents. The get method is used to retrieve the month number, and it returns “Invalid month name” if the input is not found in the dictionary.

Read How to Use the Floor() Function in Python?

3. Use the calendar Module in Python

The calendar module provides a more elegant way to handle month names and numbers. It includes the month_name attribute, which is a list of month names indexed by their month numbers.

import calendar

def month_name_to_number(month_name):
    month_name = month_name.capitalize()  # Ensure the first letter is capitalized
    try:
        month_number = list(calendar.month_name).index(month_name)
        return month_number
    except ValueError:
        return "Invalid month name"

# Example usage
month_name = "October"
month_number = month_name_to_number(month_name)
print(f"The month number for {month_name} is {month_number}.")

Output:

The month number for October is 10.

I have executed the above example code and added the screenshot below.

Convert Month Name to Number in Python calendar Module

In this example, we use the calendar.month_name list, which contains an empty string at index 0 followed by the full month names from index 1 to 12. The index method is used to find the position of the month name in the list, which corresponds to the month number.

Check out How to Use Built-In Functions in Python?

Handle Abbreviated Month Names with the calendar Module in Python

If you also need to handle abbreviated month names, you can use the month_abbr attribute from the calendar module similarly.

import calendar

def month_name_to_number(month_name):
    month_name = month_name.capitalize()  # Ensure the first letter is capitalized
    try:
        # Check full month names
        month_number = list(calendar.month_name).index(month_name)
        if month_number == 0:  # If not found, check abbreviated month names
            month_number = list(calendar.month_abbr).index(month_name)
        return month_number
    except ValueError:
        return "Invalid month name"

# Example usage
month_name = "Aug"
month_number = month_name_to_number(month_name)
print(f"The month number for {month_name} is {month_number}.")

In this code, we first check if the input matches a full month name. If not, we then check against the abbreviated month names. The calendar.month_abbr list works similarly to calendar.month_name, with abbreviated names starting from index 1.

Read How to Use the find() Function in Python?

Custom Function for Robust Conversion in Python

For a more robust solution that can handle various cases, including different capitalizations and common misspellings, you can create a custom function.

def month_name_to_number(month_name):
    month_dict = {
        "january": 1, "february": 2, "march": 3, "april": 4,
        "may": 5, "june": 6, "july": 7, "august": 8,
        "september": 9, "october": 10, "november": 11, "december": 12,
        "jan": 1, "feb": 2, "mar": 3, "apr": 4,
        "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12
    }
    month_name = month_name.lower().strip()  # Normalize the input
    return month_dict.get(month_name, "Invalid month name")

# Example usage
month_name = "  November  "
month_number = month_name_to_number(month_name)
print(f"The month number for '{month_name.strip()}' is {month_number}.")

In this example, we normalize the input by converting it to lowercase and stripping any leading or trailing whitespace. This ensures that the function can handle inputs like ” November ” or “FEB” correctly.

Read How to Use Exponential Functions in Python?

Conclusion

In this tutorial, I have explained how to convert a month name to a number in Python. I discussed some important methods to achieve this task like using datetime module , using a dictionary for conversion and using a calender module in Python. We also discussed how to handle abbreviated month names with the calendar module and how to custom function for robust conversion in Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.