Python month name to number

Get month name from number

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

For the example above, it would return Dec .

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.

mydate.strftime(«%b») returns short notation for month name. (For the example above, it would return Dec )

The OP want to use an integer as input, not a datetime.datetime object.You can use mydate = datetime.datetime(2019, integer , 1, 0, 0) but it’s rather ugly

Note that %B may return month name in wrong case if non-english locale is used. For example for ru_RU locale %B returns «января» instead of «январь».

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.

If someone is looking to do this in pandas, solution is here: stackoverflow.com/questions/36010999/…. It’s just that this is the first result that comes when looking for month name in string format question. Thought to put here in case.

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

Interesting. I Like this perspective. It might be good to point out that for this use case, the year and the numeric day of the month (1..31) are irrelevant, & would not change the output of this function call. That is why they can be hard coded with arbitrary (but valid) values. Generally it’s a good idea to highlight parts of your answer that specifically addresses OP’s issue, & point out any caveats in using your code. Explanations increase long term value, promote spreading of knowledge, & increases likelihood of upvotes. Code-only answers are generally discouraged, to keep SO quality high

Also, It’d be beneficial to include what %B stands for here, so future visitors can quickly understand how/why this function, and your code, works, and can immediately apply it to their own code. Explanations facilitate Rapid uptake of knowledge, providing a completely self-explanatory solution ;-).

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.

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 . 

thank you for your answer. if i might add a suggestion, you could add some examples of input and outputs to show how to use this code and the difference between month_name and month_abbr

This is helpful, I suggest using range(1, 13) in your example so you get all 12 months in the output.

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.

Читайте также:  Нахождение простых множителей числа python

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

Good addition, just I suggest to add a fallback culture or just wrap the setLocale call in a try/except, because if that culture is not available you get an exception (happened just to me after trying this ;))

I think I’ll leave the code as is because setting the locale is probably not something you would do anyway near that code. I just wanted to highlight how setting the locale also impact the values from calendar . I can maybe update the text.

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) 

(This Was The Real Date When I Wrote This)

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. 

Источник

Convert Month Name to Number in Python

In this post, we will see how to convert Month name to number in Python.

When representing a date in Python, the user can decide what way they want to show it. The month, in general, can be represented either by its name/abbreviation or even by a number corresponding to that particular month. Therefore, it is essential to have a process to convert from one representation to another. This tutorial demonstrates the different ways available to convert month name to month number in Python.

How to convert month name to number in Python?

There are several ways to implement the task of converting month name to number in Python, ranging from creating user-defined functions to utilizing functions from pre-existing libraries, all of which have been described in the article below.

Creating a user-defined function and utilizing it to convert month name to number in Python.

We can simply create a user-defined function, where we define a dictionary that holds all the values of the month names and the numbers equivalent to them respectively. The function can then be tackled to deal with either the month names or the month name abbreviations, as per the programmer’s needs.

In our example code, we will be making the necessary changes to the code in order to deal with month name abbreviations.

The following code creates a user-defined function and uses it to convert month name to month number in Python.

The above code provides the following output:

Using the calendar module to create a dictionary and utilize it to convert month name to number in Python.

Python provides a built-in module calendar that enables the user to deal with all calendar operations. It provides additional functions and classes related to calendar operations.

The calendar module can simply be utilized to create a dictionary that converts and stores the data of conversion of the month name to month number in Python. This method also utilizes the enumerate() function.

The following code uses the calendar module to create a dictionary and utilize it to convert month name to number in Python.

print ( dict ( ( month , index ) for index , month in enumerate ( calendar . month_abbr ) if month ) )

The above code provides the following output:

Further reading:

Get last day of month in Python
Get Today’s Date in Python

Using dict comprehension and the calendar module to convert month name to number in Python.

Dict comprehension is a compact and efficient way to create dictionaries in Python. Chunks of dictionary code can be minimized to a single line with the help of this method. It works similar to the more popular list comprehensions in Python.

The dict comprehension feature was introduced in Python 2.7 and is accepted in all the versions released after it.

The following code uses dict comprehension and the calendar module to convert month name to number in Python.

The above code provides the following output:

Using the strptime() function from the datetime module to convert month name to number in Python.

The strptime() function is utilized to convert a string object into a datetime object, given the string follows a specified format.

This function can be utilized to deal with both month names and month abbreviations and is able to successfully implement the task of converting month names to numbers in Python.

We will give an example to convert both of these types to number in Python. The month name can be converted by utilizing the ‘%B’ sign as an argument to the strptime() function while the three-letter month abbreviation can be converted by utilizing the ‘%b’ sign as an argument to the strptime() function.

First, let us look at how we can convert month name to number by utilizing the strptime() function.

Источник

How to change month name to a number?

I started learing python this month. I am a beginner so I am having problems with changing month name to numbers. I tried using if command but it does not work. The code that I use is:

d = int(input()) m = input() y = int(input()) a = y - 1900 if m == january: x = 1 print(f'It is days, months and years at .') 

But it does not work and the program shows me that name january is not defined. How can I change name of months to numbers?

Kindly follow the link below for an answer to a similar question: stackoverflow.com/questions/3418050/…

6 Answers 6

Your January isn’t in quotes so Python reads it as a variable. It should be m == ‘January’ to make it work.

you should use strptime module.

from time import strptime input_month = 'January' input_month = input_month[:3] strptime(input_month,'%b').tm_mon 

the program shows me that name january is not defined

To explain, Python looks at your program and needs to know which are variables and which are strings . When you use january without quotes (‘), the Python interpreter thinks you want to use january as a variable. It looks for the january variable, but cannot find it, because it doesn’t exist.

What you need is probably to compare if m.lower() to the string, january. To do this, all you need is to wrap january in either single quotes (‘), or double quotes («) (Python accepts both).

The line will look like this:

Источник

Converting a month name to the corresponding number. (Python)

If I input January 1 2000 for my birthday I get January/1/2000 but the output I want is 1/1/2000. Any advice?

Why ask the user to type in the month name and the date components separately? What if they mis-type it? Why not simply ask for birth date in a specific format e.g. YYYY-MM-DD?

2 Answers 2

You need a way to map the month name to the number representing the month. This can be done with a list or dictionary. Below we have a list of months. The number representing that month is simply the index of the month in the list + 1:

print("What month were you born?") m = input() print("What day were you born?") d = input() print("What year were you born?") y = input() months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] print("Your birthday is " + str(months.index(m)+1) + "/" + d + "/" + y) 

You can build upon this and add code to make the input case-insensitive and catch exceptions if the user enters the wrong value.

Great. Welcome to Stack Overflow. Consider accepting the answer if it has solved your problem. Here is the etiquette on SO: stackoverflow.com/help/someone-answers

print("What month were you born?") m = input() newm = 'lol' if m == "January" or "january": newm = '1' if m == "February" or "february": newm = '2' #KEEP GOING TILL DECEMBER print("What day were you born?") d = input() print("What year were you born?") y = input() print("Your birthday is " + newm + "/" + d + "/" + y) 

The other comments here are suggesting things that aren’t on your level of skill. I think this answers your question in a way that you can understand what is happening.

When you get better, there are better ways to go about doing this, such what the other comments have suggested. There are even better ways of doing this code lol such as ignoring case on January/january.

Источник

Оцените статью