如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
当前回答
'01'到'Jan'
from datetime import datetime
datetime.strptime('01', "%m").strftime("%b")
其他回答
import datetime
mydate = datetime.datetime.now()
mydate.strftime("%B")
返回:12月
更多信息请访问Python文档网站
[编辑:来自@GiriB的精彩评论]你也可以使用%b,它返回月份名称的简短符号。
mydate.strftime("%b")
对于上面的例子,它将返回12月12日。
日历火
从那里你可以看到那个日历。month_name[3]将返回March,数组索引为0是空字符串,因此也不需要担心零索引。
这里来自一个相关的SO问题,关于生成月份名称列表。
关于这个问题的许多选项,就像这个,建议使用日历模块,尽管datetime列表推导式也是可能的:
month_names = [dt.datetime.strptime(str(n), '%m').strftime('%B') for n in range(1, 13)]
如果您是从为大量整数查找月份名称的角度来处理这个问题的,那么为预先生成的列表建立索引可能会提高效率。
这个脚本展示了如何获得数据帧中月份变量/列的日历月缩写。注意,假设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")