如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
如何从月份编号中获得月份名称?
例如,如果我有3,我想返回march
date.tm_month()
如何获得弦乐进行曲?
当前回答
日历火
从那里你可以看到那个日历。month_name[3]将返回March,数组索引为0是空字符串,因此也不需要担心零索引。
其他回答
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
(这是我写这篇文章的真实日期)
日历火
从那里你可以看到那个日历。month_name[3]将返回March,数组索引为0是空字符串,因此也不需要担心零索引。
一些好的答案已经使用了日历,但是设置语言环境的效果还没有被提及。
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()[…]
datetime -基本日期和时间类型- Python文档
所有strftime格式代码的列表。月份的名称,以及格式化左零填充之类的好东西。阅读整页的内容,比如“天真”参数的规则。以下是清单的简要内容:
%a Sun, Mon, …, Sat
%A Sunday, Monday, …, Saturday
%w Weekday as number, where 0 is Sunday
%d Day of the month 01, 02, …, 31
%b Jan, Feb, …, Dec
%B January, February, …, December
%m Month number as a zero-padded 01, 02, …, 12
%y 2 digit year zero-padded 00, 01, …, 99
%Y 4 digit Year 1970, 1988, 2001, 2013
%H Hour (24-hour clock) zero-padded 00, 01, …, 23
%I Hour (12-hour clock) zero-padded 01, 02, …, 12
%p AM or PM.
%M Minute zero-padded 00, 01, …, 59
%S Second zero-padded 00, 01, …, 59
%f Microsecond zero-padded 000000, 000001, …, 999999
%z UTC offset in the form +HHMM or -HHMM +0000, -0400, +1030
%Z Time zone name UTC, EST, CST
%j Day of the year zero-padded 001, 002, …, 366
%U Week number of the year zero padded, Days before the first Sunday are week 0
%W Week number of the year (Monday as first day)
%c Locale’s date and time representation. Tue Aug 16 21:30:00 1988
%x Locale’s date representation. 08/16/1988 (en_US)
%X Locale’s time representation. 21:30:00
%% literal '%' character.