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

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

date.tm_month()

如何获得弦乐进行曲?


当前回答

import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")

返回:12月

更多信息请访问Python文档网站


[编辑:来自@GiriB的精彩评论]你也可以使用%b,它返回月份名称的简短符号。

mydate.strftime("%b")

对于上面的例子,它将返回12月12日。

其他回答

这就是我要做的:

from datetime import *

months = ["Unknown",
          "January",
          "Febuary",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"]

now = (datetime.now())
year = (now.year)
month = (months[now.month])
print(month)

输出:

>>> September

(这是我写这篇文章的真实日期)

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

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

一次打印所有月份:

 import datetime

 monthint = list(range(1,13))

 for X in monthint:
     month = datetime.date(1900, X , 1).strftime('%B')
     print(month)

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

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

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

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