Python程序从月号中获取月名
给定一个日期时间对象或月份数,任务是编写一个Python程序来从中获取相应的月份名称。
例子:
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.
方法 #1:使用strftime() + %B
在此,我们使用 strftime() 将日期对象转换为使用格式的字符串,并通过提供 %B 强制返回月份名称。
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))
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))
输出:
The original date is : 2020-04-08 00:00:00
Month Name from Date : April
方法#2:使用日历库和月份数
在这个变体中,不是将日期时间对象作为输入,而是接受月份名称作为输入,结果是返回的月份名称。
蟒蛇3
# 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))
输出:
The original month number is : 5
Month Name from Number : May