如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
当前回答
如果你只需要知道给定数字(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
...
其他回答
如果你只需要知道给定数字(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
...
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'
日历火
从那里你可以看到那个日历。month_name[3]将返回March,数组索引为0是空字符串,因此也不需要担心零索引。
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")
返回:12月
更多信息请访问Python文档网站
[编辑:来自@GiriB的精彩评论]你也可以使用%b,它返回月份名称的简短符号。
mydate.strftime("%b")
对于上面的例子,它将返回12月12日。
一些好的答案已经使用了日历,但是设置语言环境的效果还没有被提及。
Calendar根据当前地区设置月份名称,例如在法语中:
import locale
import calendar
locale.setlocale(locale.LC_ALL, 'fr_FR')
assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'
如果您计划在代码中使用setlocale,请确保阅读文档中的提示和警告以及扩展编写器部分。这里显示的示例不能代表它应该如何使用。特别是这两个部分:
在某些库例程中调用setlocale()通常不是一个好主意,因为它会影响整个程序[…] 扩展模块永远不应该调用setlocale()[…]