如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
当前回答
而不是导入或下载一个新的库,你可以使用我的手动功能:
将代码复制到一个新的.py文件并运行它
快速的解释:
更改your_number并输出month_from_number,您将得到月份
your_number = 10
def num_to_month(*args, **kwargs):
num = kwargs.get("num", None)
if int(num) <= 12 and int(num) > 0:
list_of_months = {'1': 'January', '2': 'February', '3': 'March',
'4': 'April', '5': 'May', '6': 'June', '7': 'July',
'8': 'August', '9': 'September', '10': 'October',
'11': 'November', '12': 'December'}
return list_of_months[num]
else:
print('num_to_month function error: "num=' + str(num) + '"')
month_from_num = num_to_month(num=your_number)
print(month_from_num)
结果将在10月份公布
其他回答
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")
返回:12月
更多信息请访问Python文档网站
[编辑:来自@GiriB的精彩评论]你也可以使用%b,它返回月份名称的简短符号。
mydate.strftime("%b")
对于上面的例子,它将返回12月12日。
如果你只需要知道给定数字(1 - 12)的月份名称,这就不太有用了,因为当前日期并不重要。
calendar.month_name[我]
or
calendar.month_abbr[我]
在这里更有用。
这里有一个例子:
import calendar
for month_idx in range(1, 13):
print (calendar.month_name[month_idx])
print (calendar.month_abbr[month_idx])
print ("")
样例输出:
January
Jan
February
Feb
March
Mar
...
对于任意范围的月份数字
month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)
将产生正确的列表。从月份-整数列表中一月份开始的位置调整start-parameter。
这里来自一个相关的SO问题,关于生成月份名称列表。
关于这个问题的许多选项,就像这个,建议使用日历模块,尽管datetime列表推导式也是可能的:
month_names = [dt.datetime.strptime(str(n), '%m').strftime('%B') for n in range(1, 13)]
如果您是从为大量整数查找月份名称的角度来处理这个问题的,那么为预先生成的列表建立索引可能会提高效率。
datetime -基本日期和时间类型- Python文档
所有strftime格式代码的列表。月份的名称,以及格式化左零填充之类的好东西。阅读整页的内容,比如“天真”参数的规则。以下是清单的简要内容:
%a Sun, Mon, …, Sat
%A Sunday, Monday, …, Saturday
%w Weekday as number, where 0 is Sunday
%d Day of the month 01, 02, …, 31
%b Jan, Feb, …, Dec
%B January, February, …, December
%m Month number as a zero-padded 01, 02, …, 12
%y 2 digit year zero-padded 00, 01, …, 99
%Y 4 digit Year 1970, 1988, 2001, 2013
%H Hour (24-hour clock) zero-padded 00, 01, …, 23
%I Hour (12-hour clock) zero-padded 01, 02, …, 12
%p AM or PM.
%M Minute zero-padded 00, 01, …, 59
%S Second zero-padded 00, 01, …, 59
%f Microsecond zero-padded 000000, 000001, …, 999999
%z UTC offset in the form +HHMM or -HHMM +0000, -0400, +1030
%Z Time zone name UTC, EST, CST
%j Day of the year zero-padded 001, 002, …, 366
%U Week number of the year zero padded, Days before the first Sunday are week 0
%W Week number of the year (Monday as first day)
%c Locale’s date and time representation. Tue Aug 16 21:30:00 1988
%x Locale’s date representation. 08/16/1988 (en_US)
%X Locale’s time representation. 21:30:00
%% literal '%' character.