How to find name of month in Python?

In today’s article of Python tip series, let us see how to find the name of the month form a number and from a given date.

Month name from number

To get the month’s name from the month number, you can use the calendar.month_name array or the calendar.month_abbr array in the calendar module. calendar.month_name is an array which represents the full month name on the other hand calendar.month_abbr represents the abbreviated month names. Here is a sample code.

import calendar

for month_no in range(1,13):
     print(month_no, ":", calendar.month_abbr[month_no], " -> ", calendar.month_name[month_no])
Python: Get month name from number

Name of the month from date

To get the month’s abbreviated and full name from a given date, use either the month_name / month_abbr arrays or the strftime() method from the datetime module. Here is a sample source code which uses both the methods.

from datetime import datetime
import calendar

given_date = datetime(year=2012, month=6, day=14)

# strftime method
month_short = given_date.strftime('%b')
month_long = given_date.strftime('%B')

print("\nShort and long month name: ", month_short, " -> ", month_long)

# month_name / month_abbr method
month_short = calendar.month_abbr[given_date.month]
month_long = calendar.month_name[given_date.month]

print("\nShort and long month name: ", month_short, " -> ", month_long)
Month name from date in Python

Mote Tips

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.