Get month name from number

2019-01-04 07:53发布

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?

9条回答
叛逆
2楼-- · 2019-01-04 08:35

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

...
查看更多
对你真心纯属浪费
3楼-- · 2019-01-04 08:37

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.

查看更多
SAY GOODBYE
4楼-- · 2019-01-04 08:46
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.

查看更多
Deceive 欺骗
5楼-- · 2019-01-04 08:46

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.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-04 08:48

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
查看更多
The star\"
7楼-- · 2019-01-04 08:55
import datetime

monthinteger = 4

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

print month

April

查看更多
登录 后发表回答