如何从月份编号中获得月份名称?

例如,如果我有3,我想返回march

date.tm_month()

如何获得弦乐进行曲?


当前回答

一些好的答案已经使用了日历,但是设置语言环境的效果还没有被提及。

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()[…]

其他回答

对于任意范围的月份数字

month_integer=range(0,100)
map(lambda x: calendar.month_name[x%12+start],month_integer)

将产生正确的列表。从月份-整数列表中一月份开始的位置调整start-parameter。

这个脚本展示了如何获得数据帧中月份变量/列的日历月缩写。注意,假设month列/变量的值都是数字,可能会有一些缺失的值。

# Import the calendar module
  import calendar
    
# Extract month as a number from the date column
  df['Month']=pd.DatetimeIndex(df['Date']).month

# Using list comprehension extract month abbreviations for each month number
 df['Month_abbr']=[calendar.month_abbr[int(i)] if pd.notna(i) else i for i in df['Month']]

'01'到'Jan'

from datetime import datetime

datetime.strptime('01', "%m").strftime("%b")    
import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

4月

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B") # 'December'
mydate.strftime("%b") # 'dec'