Skip to content
Related Articles

Related Articles

Improve Article

Python program to Get Month Name from Month Number

  • Last Updated : 09 May, 2021

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

Examples:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 :