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

例如,如果我有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

...

其他回答

对于任意范围的月份数字

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

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

'01'到'Jan'

from datetime import datetime

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

这个脚本展示了如何获得数据帧中月份变量/列的日历月缩写。注意,假设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']]

如果(像我一样)你在数据框架中有一列月份数字,我会提供这个:

df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])

这里来自一个相关的SO问题,关于生成月份名称列表。

关于这个问题的许多选项,就像这个,建议使用日历模块,尽管datetime列表推导式也是可能的:

month_names = [dt.datetime.strptime(str(n), '%m').strftime('%B') for n in range(1, 13)]

如果您是从为大量整数查找月份名称的角度来处理这个问题的,那么为预先生成的列表建立索引可能会提高效率。