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

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

date.tm_month()

如何获得弦乐进行曲?


当前回答

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

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

其他回答

而不是导入或下载一个新的库,你可以使用我的手动功能:

将代码复制到一个新的.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日。

'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月

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