Python date month name

How to get Month Name Short Version using Python datetime?

To get Month Name Short Version using Python datetime, call strftime() with %b passed as argument.

Month Output
January Jan
February Feb
March Mar
April Apr
May May
June Jun
July Jul
August Aug
September Sep
October Oct
November Nov
December Dec

Examples

1. Get month name short version from current date

In the following example, we will take the current date, and get the day of month.

Python Program

#import datetime package import datetime #get current time d = datetime.datetime.now() #print date print(d) #get month name short version print(d.strftime("%b"))
2019-06-26 08:50:36.787821 Jun

2. Get month name short version from given date

In the following example, we will take a date 2019-08-12 and get the day of month.

Python Program

#import datetime package import datetime #set specific date d = datetime.datetime(2019, 8, 12) #print date print(d) #get month name short version print(d.strftime("%b"))

Summary

In this tutorial, we extracted the month name short version from date using datetime package.

Источник

Python Get Month Name From Number

In Python, you can use the calendar module’s calendar.month_name[number] attribute to get the month name from a given number.

For example, month_name = calendar.month_name[6] will give you June as an output. If you have a datetime object, datetime(2022, 10, 12, 18, 45, 56) , then it will return October as a month name.

In this lesson, you’ll learn how to:

  • Get the month name from a month number. i.e., convert the month number to the month’s full name (like December) and short name (like Dec).
  • Get the month’s name from a date.
  • Convert month name to month number and vice versa.

Table of contents

How to Get Month Name from Number in Python

We can use two ways to get the month name from a number in Python. The first is the calendar module, and the second is the strftime() method of a datetime module. The below steps show how to get the month name from a number in Python using the calendar module.

  1. Import calendar module Calendar is a built-in module available in Python. This module allows you to output calendars like the Unix cal program and provides additional useful functions related to the calendar.
  2. Use calendar.month_name data attribute Use the calendar.month_name[number] attribute to get the month’s full name from a number.

The calendar.month_name[num] is an array that represents the months of the year in the current locale. This follows the standard convention of January being month number 1, so it has a length of 13 and calendar.month_name[0] is the empty string.

Example: Get Month Name from Number in Python

import calendar num = 2 print('Month Number:', num) # get month name print('Month full name is:', calendar.month_name[num])
Month Number: 2 Month full name is: February

Also, you can get all month’s names using this data attribute.

import calendar # get all months name using number for i in range(1, 13): # get month name print('Month full name is:', calendar.month_name[i]) print('Month short name is:', calendar.month_abbr[i])

Get Abbreviated Month Name from Number in Python

If you want to convert the month number to an abbreviated month name, then use the calendar.month_abbr data attribute.

For example, calendar.month_abbr[2] will return Feb as a month name. Note: Feb is the short name of February month.

To get the abbreviated month name from a number, you can use the following code:

import calendar month_number = 2 print('Month Number:', month_number) print('Month short name is:', calendar.month_abbr[month_number])

Get Month Name from Datetime in Python

Use the below code to get the month name from a datetime object.

  • First, extract the month number from a datetime object using the month attribute.
  • Next, use the calendar.month_name[num] attribute to get the month name.
from datetime import datetime import calendar dob = datetime(1994, 8, 24) print('DateTime:', dob) # get month number num = dob.month print('Month Number:', num) # get month name print('Month full name is:', calendar.month_name[num]) print('Month short name is:', calendar.month_abbr[num])
DateTime: 1994-08-24 00:00:00
Month Number: 8
Month full name is: August
Month short name is: Aug

Get Month Name from Datetime using strftime()

The strftime() method represents datetime in string formats. Use the datetime.strftime(format) to convert a datetime object into a string as per the corresponding format.

The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

In our case, we need the month name, so we must use the two directives below.

  • %B : Returns the full name of the month. Like, June, March
  • %b : Returns the short name of the month (First three characters). Like, Mar, Jun
from datetime import datetime # get today's datetime now = datetime.now() print('DateTime:', now) print('Month Number:', now.month) print('Month full name:', now.strftime('%B')) print('Month short name:', now.strftime('%b'))
DateTime: 2022-10-12 15:18:09.688342 Month Number: 10 Month full name: October Month short name: Oct

Convert Month Name to Month Number in Python

Now, let’s see how to convert a month name to a month number. We will also see how to convert a month number to an abbreviated month name or an abbreviated month name to a month number.

Using this example, you can map the month name to the month number and vice versa.

import calendar from datetime import datetime dob = datetime(1994, 8, 24) print('DateTime:', dob) # get month number num = dob.month print('Month Number:', num) # month number to month name fn = calendar.month_name[num] print('Month full name is:', fn) sn = calendar.month_abbr[num] print('Abbreviated month name is:', sn) # convert month name to number # Get month number from full month name f_mn = list(calendar.month_name).index(fn) print('Month Number:', f_mn) # Get month number from abbreviated month name s_mn = list(calendar.month_abbr).index(sn) print('Month Number:', s_mn) 
DateTime: 1994-08-24 00:00:00 Month Number: 8 Month full name is: August Abbreviated month name is: Aug Month Number: 8 Month Number: 8

Convert Month Number to Month name in pandas

If you are working with a pandas dataframe or series, these examples will help you. First, let’s see how to get the month name of a pandas series of multiple dates.

Use the dt.month_name() function to get the month name in pandas.

Convert pandas datetime to month name

import pandas as pd # Create a Series dates = pd.Series(['2022-1-30', '2022-4-18', '2022-7-23']) # Create index idx = [dates[0], dates[1], dates[2]] # set the index dates.index = idx dates = pd.to_datetime(dates) print('All Dates') print(dates) # Get month name print('Month name') result = dates.dt.month_name(locale='English') print(result)
All Dates 2022-1-30 2022-01-30 2022-4-18 2022-04-18 2022-7-23 2022-07-23 dtype: datetime64[ns] Month name 2022-1-30 January 2022-4-18 April 2022-7-23 July dtype: object

Convert a column of month numbers in a dataframe to a month name

If one of the columns of a pandas dataframe contains a month number, then use the below code to convert the month number to the month name.

import pandas as pd import calendar # Create dict object student_dict = # Create DataFrame from dict df = pd.DataFrame(student_dict) print('Student Details') print(df) # get months name month_names = df['join_month'].apply(lambda x: calendar.month_name[x]) print('Months Name') print(month_names) # replace column join_month df['join_month'] = month_names print('Student Details') print(df)
Student Details name join_month 0 Joe 8 1 Nat 4 2 Harry 11 Months Name 0 August 1 April 2 November Name: join_month, dtype: object Student Details name join_month 0 Joe August 1 Nat April 2 Harry November

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How to Get Month Name from Month Number in Python

In this article, we will learn how to get a month name from a month number in Python. We will use some built-in modules available and some custom codes as well to see them working. Let’s first have a quick look over what are dates in Python.

Dates in Python

In Python, we can work on Date functions by importing a built-in module datetime available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond.

Let us discuss different ways to convert a month number to a month name. We will get the month number by taking input from the user, from date, or by creating a series of dates and then converting the month number to month name. We will see that the month name can be printed in two ways. The first way is the full name of the month as of March and another way is the short name like Mar.

Example: Get Month Name from Month Number using Datetime Object

This method uses datetime module. The user gives the input for the month number. datetime.strptime() is called. It takes month number and month format «%m» as arguments. Passing «%b» to strftime returns abbreviated month name while using «%B» returns full month name.

import datetime #provide month number month_num = "3" datetime_object = datetime.datetime.strptime(month_num, "%m") month_name = datetime_object.strftime("%b") print("Short name: ",month_name) full_month_name = datetime_object.strftime("%B") print("Full name: ",full_month_name)

Short name: Mar
Full name: March

Example: Get Month Name from Month Number using Calendar Module

This method imports calender module. It simply uses a for loop to iterate over the number of months (12). There are two built-in arrays in the calendar module. calendar.month_name[] is an array that represents the full month name while calendar.month_abbr[] in the second array that represents the abbreviated month names. You can also assign any month number to x in order to find the equivalent month name.

import calendar for x in range(1,13): print(x, ":", calendar.month_abbr[x], "-", calendar.month_name[x]) # for month number = 4 x = 4 print(x, ":", calendar.month_abbr[x], "-", calendar.month_name[x])

1 : Jan — January
2 : Feb — February
3 : Mar — March
4 : Apr — April
5 : May — May
6 : Jun — June
7 : Jul — July
8 : Aug — August
9 : Sep — September
10 : Oct — October
11 : Nov — November
12 : Dec — December

Example: Get Month Name using Pandas Series

This method uses Pandas library of Python. In this example, we create a series of multiple dates to get corresponding month names. This is done by using pd.Series. This method is useful when you want to convert month numbers to their names from multiple dates. It creates an array for index. It sets the index array to the given series. Pandas dt.month_name() function returns the month names of the DateTimeIndex with specified locale. Locale determines the language in which the month name is returned. dt.month_name() returns the names of the month of each timestamp in the given series object.

import pandas as pd #Create a Series dates = pd.Series(['2012-12-31', '2019-1-1', '2008-02-2']) #Create index idx = ['Date 1', 'Date 2', 'Date 3'] #set the index dates.index = idx # Convert the data to datetime dates = pd.to_datetime(dates) print(dates) # return month name result = dates.dt.month_name(locale = 'English') print('\n') print(result)

Date 1 2012-12-31
Date 2 2019-01-01
Date 3 2008-02-02
dtype: datetime64[ns]

Date 1 December
Date 2 January
Date 3 February
dtype: object

Conclusion

In this article, we learned to convert month numbers to month names by using datetime module, calender module, and Pandas library. We used some custom codes as well. We printed abbreviated month names as well as full months names. We get month numbers either as an input or by extracting from a date.

Источник

Читайте также:  Html form input description
Оцените статью