从号码中获取月份名称

问题:从号码中获取月份名称

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

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

date.tm_month()

如何获得字符串march

How can I get the month name from the month number?

For instance, if I have 3, I want to return march

date.tm_month()

How to get the string march?


回答 0

日历API

从中可以看到calendar.month_name[3]它将返回March,并且的数组索引0为空字符串,因此也无需担心零索引。

Calendar API

From that you can see that calendar.month_name[3] would return March, and the array index of 0 is the empty string, so there’s no need to worry about zero-indexing either.


回答 1

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

返回:12月

有关Python文档网站的更多信息


[编辑:来自@GiriB的出色评论]您还可以使用%b它返回月份名称的缩写。

mydate.strftime("%b")

对于上面的示例,它将返回Dec

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

Returns: December

Some more info on the Python doc website


[EDIT : great comment from @GiriB] You can also use %b which returns the short notation for month name.

mydate.strftime("%b")

For the example above, it would return Dec.


回答 2

import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

四月

import datetime

monthinteger = 4

month = datetime.date(1900, monthinteger, 1).strftime('%B')

print month

April


回答 3

如果您只需要知道给定数字(1-12)的月份名称,这就没有太大帮助,因为当前日期无关紧要。

calendar.month_name[i]

要么

calendar.month_abbr[i]

在这里更有用。

这是一个例子:

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

...

This is not so helpful if you need to just know the month name for a given number (1 – 12), as the current day doesn’t matter.

calendar.month_name[i]

or

calendar.month_abbr[i]

are more useful here.

Here is an example:

import calendar

for month_idx in range(1, 13):
    print (calendar.month_name[month_idx])
    print (calendar.month_abbr[month_idx])
    print ("")

Sample output:

January
Jan

February
Feb

March
Mar

...

回答 4

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

回答 5

如果您(像我一样)在数据框中有一列月份数字,我将提供此信息:

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

I’ll offer this in case (like me) you have a column of month numbers in a dataframe:

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

回答 6

这就是我要做的:

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

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

This Is What I Would Do:

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)

It Outputs:

>>> September

(This Was The Real Date When I Wrote This)


回答 7

一些好的 答案已经利用日历了,但是尚未提到设置语言环境的效果。

例如,法语:

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()[…]

Some good answers already make use of calendar but the effect of setting the locale hasn’t been mentioned yet.

Calendar set month names according to the current locale, for exemple in French:

import locale
import calendar

locale.setlocale(locale.LC_ALL, 'fr_FR')

assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'

If you plan on using setlocale in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]

Extension modules should never call setlocale() […]


回答 8

对于arbitaray月度范围

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

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

For arbitaray range of month numbers

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

will yield correct list. Adjust start-parameter from where January begins in the month-integer list.


回答 9

8.1。datetime-基本日期和时间类型-Python 2.7.17文档 https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

所有strftime参数的列表。月份的名称以及诸如格式化之类的好东西,将零填满。阅读整页,了解诸如“天真的”参数规则之类的内容。这是简短的列表:%a周日,周一,…,星期六

%A周日,周一,…,周六

%w工作日为数字,其中0是星期日

%d每月的第一天02,…,31

%b 1月,2月,…,12月

%B一月,二月,…,十二月

%m月号,以零填充的01、02,…,12

%y 2位数字年份零填充00、01,…,99

%Y 4位数字1970、1988、2001、2013年

%H小时(24小时制),零填充00,01,…,23

%I小时(12小时制)零填充01,02,…,12

%p AM或PM。

%M分钟零填充00、01,…,59

%S第二个零填充00、01,…,59

%f微秒零填充000000,000001,…,999999

%z UTC偏移量,格式为+ HHMM或-HHMM + 0000,-0400,+ 1030

%Z时区名称UTC,EST,CST

%j一年中的当日零填充001、002,…,366

%U年份的周号零填充,第一个星期日之前的天是第0周

%W一年中的第几周(星期一作为第一天)

%c语言环境的日期和时间表示。1988年8月16日星期二21:30:00

%x语言环境的日期表示形式。1988年8月16日(zh_CN)

%X语言环境的时间表示形式。21:30:00

%%文字’%’字符。

8.1. datetime — Basic date and time types — Python 2.7.17 documentation https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

A list of all the strftime arguments. Names of months and nice stuff like formatting left zero fill. Read the full page for stuff like rules for “naive” arguments. Here is the list in brief: %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.


回答 10

我创建了自己的函数,将数字转换为相应的月份。

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

然后,我可以调用该函数。例如:

print (month_name (12))

输出:

>>> December

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December