Skip to content
Related Articles

Related Articles

Python program to Get Month Name from Month Number

View Discussion
Improve Article
Save Article
  • Last Updated : 09 May, 2021
View Discussion
Improve Article
Save Article

Given a datetime object or month number, the task is to write a Python program to get the corresponding month name from it. 

Examples:

Input : test_date = datetime(2020, 4, 8)

Output : April

Explanation : 4th Month is April.

Input : test_date = datetime(2020, 1, 8)

Output : January

Explanation : 1st Month is January.

Method #1 : Using strftime() + %B

In this, we use strftime() which converts date object to a string using a format, and by providing %B, it’s enforced to just return a Month Name.

Python3




# Python3 code to demonstrate working of
# Get Month Name from Month Number
# Using strftime() + %B
from datetime import datetime
  
# initializing date
test_date = datetime(2020, 4, 8)
               
# printing original date
print("The original date is : " + str(test_date))
  
# getting month name using %B
res = test_date.strftime("%B")
  
# printing result
print("Month Name from Date : " + str(res))

Output:

The original date is : 2020-04-08 00:00:00
Month Name from Date : April

Method #2: Using calendar library and month number

In this variant, rather than having datetime object as input, the month name as an input is accepted and the result is the month name returned.

Python3




# Python3 code to demonstrate working of
# Get Month Name from Month Number
# Using calendar library and month number
import calendar
  
# initializing month number
test_num = 5
               
# printing original month number
print("The original month number is : " + str(test_num))
  
# using month_name() to get month name 
res = calendar.month_name[test_num]
  
# printing result
print("Month Name from Number : " + str(res))

Output:

The original month number is : 5
Month Name from Number : May

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!