To convert month name to number in Python, pass the name to datetime.strptime(name, "%B").month, which turns “March” into 3.
Typed months are rarely that tidy, though. A stray space or “Sept” makes the simple version raise ValueError.
In this tutorial, I’ll show you how to convert month name to number in Python four ways, then go back from number to name. Every Command Prompt screenshot is a real Python 3.12.5 run.
The Monthly Sales Data We’ll Convert
Here are seven month cells and their USD sales from the shop’s report, saved as sales.py:
# Month cells typed into a Denver bike shop's 2026 sales report
SALES = [("January", 18420.50), ("feb", 15975.25), ("MARCH", 21310.00),
(" April", 19880.75), ("Sept", 22140.40), ("Dec", 30215.90),
("N/A", 0.00)]
Four rows are tricky on purpose: “feb”, ” April” with a leading space, “Sept” and “N/A”. Excel and Google Sheets exports look like this all the time.
Months inside full dates like “03/14/2026”? You can convert the string to a date in Python and read .month.
Method 1: Convert a Month Name to a Number with strptime() (Recommended)
datetime.strptime() already knows every English month name. The %B code matches a full name and %b matches a three-letter one, so I try both.
Same sales list here, run through month_number():
from datetime import datetime
from sales import SALES
def month_number(name):
for fmt in ("%B", "%b"): # full name, then 3-letter short name
try:
return datetime.strptime(name.strip(), fmt).month
except ValueError:
pass
return None
for name, total in SALES:
print(f"{name!r:>10} -> {month_number(name)!s:>4} ${total:,.2f}")
Output:
'January' -> 1 $18,420.50
'feb' -> 2 $15,975.25
'MARCH' -> 3 $21,310.00
' April' -> 4 $19,880.75
'Sept' -> None $22,140.40
'Dec' -> 12 $30,215.90
'N/A' -> None $0.00

That converts January, feb, MARCH, April and Dec to 1, 2, 3, 4 and 12, while Sept and N/A return None.
How does this code work?
strptime() parses the text into a datetime in 1900, on day 1 of the month it found. You only keep .month, so the made-up year and day never matter.
Matching ignores case, which is why “feb” and “MARCH” pass. .strip() removes the space before April; without it, the parse fails.
When neither format fits, ValueError is raised and the loop moves on. Catch only that error (more on catching exceptions in Python), not a bare except.
“Sept” fails with “unconverted data remains: t” because %b eats “Sep” and the “t” is left over. Full format-code tables are in my post on converting a string to datetime in Python.
Method 2: Look Up Month Numbers with the Python calendar Module
For thousands of cells, a dictionary lookup beats parsing each one. Python’s calendar.month_name and calendar.month_abbr give you the names to build it from.
Same seven months again, now through one lookup table:
import calendar
from sales import SALES
LOOKUP = {m.lower(): n for n, m in enumerate(calendar.month_name) if m}
LOOKUP |= {a.lower(): n for n, a in enumerate(calendar.month_abbr) if a}
LOOKUP["sept"] = 9 # common US short form
print(len(LOOKUP), "keys:", LOOKUP["march"], LOOKUP["mar"])
for name, total in SALES:
print(f"{name!r:>10} -> {LOOKUP.get(name.strip().lower())}")
print(calendar.Month["MARCH"].value, calendar.Month(9).name) # 3.12+
Output:
24 keys: 3 3
'January' -> 1
'feb' -> 2
'MARCH' -> 3
' April' -> 4
'Sept' -> 9
'Dec' -> 12
'N/A' -> None
3 SEPTEMBER

Now Sept maps to 9. The table holds 24 keys, not 25, because May’s full and short names match.
How does this code work?
Both lists start with an empty string at index 0, so position 1 is January. enumerate() in Python hands us that position as the month number, and if m skips the blank.
Each line is a dictionary comprehension, and |= merges the second into the first (Python 3.9+). Keys are lowercase, so you lowercase the input before .get().
On Python 3.12+, calendar.Month["MARCH"].value gives 3 too. It wants the uppercase English name, so it’s an extra, not a parser for typed text.
Important: a quick list(calendar.month_abbr).index(name) looks tempting, but in my run a blank cell returned 0 instead of an error, and “mar” wasn’t found because the list is title case.
Method 3: Match Month Names by Prefix in Python (No Imports)
Sometimes you can’t predict the spelling: “September”, “Sept”, “sept.” and “Sep” in one column. Matching the start of the full name handles all of them.
Here’s a slicing version next to a prefix version, so you can see why I prefer the second:
MONTHS = ("january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november",
"december")
SHORT = {m[:3]: n for n, m in enumerate(MONTHS, 1)}
def by_slice(name):
return SHORT.get(name.strip()[:3].lower())
def by_prefix(name):
key = name.strip().rstrip(".").lower()
for number, month in enumerate(MONTHS, 1):
if len(key) >= 3 and month.startswith(key):
return number
return None
for name in ["September", "Sept", "sept.", " April", "Junk", "N/A"]:
print(f"{name!r:>12} slice: {by_slice(name)!s:>4}"
f" prefix: {by_prefix(name)}")
Output:
'September' slice: 9 prefix: 9
'Sept' slice: 9 prefix: 9
'sept.' slice: 9 prefix: 9
' April' slice: 4 prefix: 4
'Junk' slice: 6 prefix: None
'N/A' slice: None prefix: None

Both read September, Sept, sept. and April correctly, but slicing maps “Junk” to 6, while the prefix check returns None.
How does this code work?
by_slice() keeps the first three letters, so anything starting with “jun” looks like June. by_prefix() asks the opposite question: does a real month name start with what was typed?
len(key) >= 3 stops “ma” matching March; .rstrip(".") drops the period from “sept.”.
Real typos like “Febuary” still fail both. If you see many of those, fuzzy string matching in Python can pick the closest month name.
Convert a pandas Column of Month Names to Numbers
For a CSV or Excel export, convert the whole column at once. Same sales list, loaded into a pandas 3.0.6 DataFrame and converted two ways:
import calendar
import pandas as pd
from sales import SALES
ABBR = {a.lower(): n for n, a in enumerate(calendar.month_abbr) if a}
df = pd.DataFrame(SALES, columns=["month", "sales"])
clean = df["month"].str.strip()
strict = pd.to_datetime(clean, format="%B", errors="coerce")
df["strict"] = strict.dt.month.astype("Int64")
df["number"] = clean.str[:3].str.lower().map(ABBR).astype("Int64")
print(df)
print("Sales with a month:", f"${df.dropna(subset=['number'])['sales'].sum():,.2f}")
Output:
month sales strict number
0 January 18420.50 1 1
1 feb 15975.25 <NA> 2
2 MARCH 21310.00 3 3
3 April 19880.75 4 4
4 Sept 22140.40 <NA> 9
5 Dec 30215.90 <NA> 12
6 N/A 0.00 <NA> <NA>
Sales with a month: $127,942.80

The strict column fills in January, MARCH and April only. The mapped column also gets feb, Sept and Dec, and the six rows with a month add up to $127,942.80.
How does this code work?
pd.to_datetime(..., format="%B", errors="coerce") turns anything that isn’t a full name into NaT. The .str[:3].str.lower().map(ABBR) chain looks up the first three letters, so “Sept” maps to 9.
astype("Int64") keeps whole numbers and shows <NA> for misses. For date strings rather than bare month names, convert the pandas column to datetime and use .dt.month.
Convert a Month Number to a Month Name in Python
Going the other way is a plain index. Python’s calendar.month_name[3] is “March” and calendar.month_abbr[3] is “Mar”:
import calendar
from datetime import date
for number in (3, 9, 12):
print(number, calendar.month_name[number], calendar.month_abbr[number])
order_day = date(2026, 11, 26)
print("From a date:", order_day.month, order_day.strftime("%B"),
order_day.strftime("%b"))
print("Index 0: ", repr(calendar.month_name[0]))
print("Index -1:", calendar.month_name[-1]) # no error!
try:
calendar.month_name[13]
except IndexError as err:
print("Index 13: IndexError:", err)
Output:
3 March Mar
9 September Sep
12 December Dec
From a date: 11 November Nov
Index 0: ''
Index -1: December
Index 13: IndexError: list index out of range
