开发者

Get month name from number

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?


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.


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.


import datetime

monthinteger = 4

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

print month

April


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

...


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


To print all months at once:

 import datetime

 monthint = list(range(1,13))

 for X in monthint:
     month = datetime.date(1900, X , 1).strftime('%B')
     print(month)


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])


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


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)


datetime — Basic date and time types — Python documentation

A list of all the strftime format codes. 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.


'01' to 'Jan'

from datetime import datetime

datetime.strptime('01', "%m").strftime("%b")    


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.


instead of import or downloading a new lib, you can use my manual function:

copy the code to a new .py file and run it

quick explanation:

change your_number and print month_from_number, you will get the month

    your_number = 10

    def num_to_month(*args, **kwargs):

        num = kwargs.get("num", None)

        if int(num) <= 12 and int(num) > 0:

            list_of_months = {'1': 'January', '2': 'February', '3': 'March',
                              '4': 'April', '5': 'May', '6': 'June', '7': 'July',
                              '8': 'August', '9': 'September', '10': 'October',
                              '11': 'November', '12': 'December'}

            return list_of_months[num]

        else:

            print('num_to_month function error: "num=' + str(num) + '"')

    month_from_num = num_to_month(num=your_number)

    print(month_from_num)

the result will be October


This script is to show how to get calendar month abbreviations for a month variable/column in a data frame. Note that the assumption is that the values of the month column/variable are all numbers and maybe there might be some missing values.

# 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']]


If you just have the month number and not a datetime instance you could built a small function to map number with label as this:

def monthname(m):
    d={1:'En',2:'Fe',3:'Mr',4:'Ab',5:'My',6:'Jn',7:'Jl',8:'Ag',9:'Se',10:'Oc',11:'No',12:'Di'}
    return d[m]


Came here from a related SO question about generating a list of month names.

Many of the options on that question, as this one, suggested the calendar module, though the same is possible with a datetime list comprehension:

month_names = [dt.datetime.strptime(str(n), '%m').strftime('%B') for n in range(1, 13)]

Should you be approaching this question from the perspective of looking up month names for a large number of integers, indexing a pre-generated list may have efficiency benefits.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜