Convert python abbreviated month name to full name

11,807

Solution 1

If you insist on using datetime as per your tags, you can convert the short version of the month to a datetime object, then reformat it with the full name:

import datetime
datetime.datetime.strptime('apr','%b').strftime('%B')

Solution 2

Here is a method to use calendar library.

>>> import calendar
>>> calendar.month_name [list(calendar.month_abbr).index('Apr')]
'April'
>>>

Solution 3

import calendar
months_dict = dict(zip(calendar.month_abbr[1:], calendar.month_name[1:]))
# {'Jan': 'January', 'Feb': 'February', 'Mar': 'March', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July', 'Aug': 'August', 'Sep': 'September', 'Oct': 'October', 'Nov': 'November', 'Dec': 'December'}

Make sure you convert to proper cases based on your need.

Similarly, calendar library also has calendar.day_abbr and calendar.day_name

Solution 4

a simple dictionary would work

eg

month_dict = {"jan" : "January", "feb" : "February" .... }

month_dict["jan"]

'January'

Solution 5

One quick and dirty way:

conversions = {"Apr": "April", "May": "May", "Dec": "December"}
date = "Apr"

if date in conversions:
    converted_date = conversions[date]
Share:
11,807
user308827
Author by

user308827

Updated on June 04, 2022

Comments

  • user308827
    user308827 almost 2 years

    How can I convert an abbreviated month anme e.g. Apr in python to the full name?

  • Afsan Abdulali Gujarati
    Afsan Abdulali Gujarati over 5 years
    Why isn't it able to parse Sept as September which is one of the standard abbreviations of September? Any other way to handle it through some library?
  • Andras Deak -- Слава Україні
    Andras Deak -- Слава Україні over 5 years
    @AfsanAbdulaliGujarati the datetime library was written this way. See for instance strftime.org, which says %b is "Month as locale’s abbreviated name" and shows 'Sep' specifically as an example. I suspect that the abbreviation depends on the locale, so in certain locales it may be possible that 'Sept' is parsed. Anyway, some of the other answers use a manual mapping from long to short month name; these solutions can straightforwardly be used to define your own abbreviations ('Sept' included).
  • Afsan Abdulali Gujarati
    Afsan Abdulali Gujarati over 5 years
    The only thing that worries me about the manual mapping is missing out on other possible abbreviations out there. I happened to somehow stumble upon the Sept thing.
  • Andras Deak -- Слава Україні
    Andras Deak -- Слава Україні over 5 years
    @AfsanAbdulaliGujarati well the only automatically correct version is what comes with the locale. Any other choice is arbitrary, so you will have to you explicitly specify what you expect to parse yourself. You need to know your data anyway if it's in a non-standard format.