python ylabel 從號碼獲取月份名稱




python title position (7)

我創建了自己的函數將數字轉換為相應的月份。

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

我怎樣才能從月份號碼中獲得月份名稱?

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

date.tm_month()

如何獲得字符串march


日曆API

從這裡你可以看到calendar.month_name[3]會返回March ,而數組索引0是空字符串,所以不需要擔心零索引。


如果您只需要知道給定數字(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

...

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

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

返回: 十二月

關於Python doc網站的更多信息

[編輯:來自@GiriB的精彩評論]您還可以使用%b返回月份名稱的簡短符號。

mydate.strftime("%b")

對於上面的例子,它會返回Dec


import datetime

monthinteger = 4

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

print month

四月


這是我會做的事情:

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

(這是我寫的這個真實的日期)





date