Home > Net >  Convert MM-DD-YYYY into MonthName-DD-YYYY [duplicate]
Convert MM-DD-YYYY into MonthName-DD-YYYY [duplicate]

Time:10-02

How to convert 10-03-2021 into October-03-2021?

I have column in data frame in MM-DD-YYYY which needs to be converted into Month Name- Date- Year

example

10-03-2021 into October-03-2021

CodePudding user response:

You have two parts: parsing the date, and then printing it with your format.

Parsing is quite easy with the lubridate package:

> library(lubridate)
> dates <- mdy(c('10-03-2021', '01-31-1995'))
> dates
[1] "2021-10-03" "1995-01-31"

For printing, you can then use the format() function:

> format(dates, '%B-%d-%Y')
[1] "October-03-2021" "January-31-1995"

%B is the full name of the month, %d the day and %Y the year (with all 4 digits)

CodePudding user response:

I have created a function that should do exactly what you want. The function is called when changing the dates in the Dataframe itself. I assumed that your Date column is called 'Date'; however, if that is not the case feel free to change the column name.

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

def convert_dates(x):
    month_int = int(x[3:5])
    month_str = months_conversion[str(month_int)]
    days = int(x[0:2])
    year = int(x[-4:])
    new_date = f'{month_str}-{days}-{year}'
    return new_date


df['Date'] = df['Date'].apply(convert_dates)
  • Related