2

I have a string as follows

11MAY2018:00:00:00.000 

Can this be converted to the following formats

i) 11-May-2018

ii) May-2018 or 05-2018

2 Answers 2

4

You can use lubridate package to turn your string into a date format and then use some functions like year, month, day to extract relevant information and combine them using paste0:

library(lubridate) x = "11MAY2018:00:00:00.000" y = dmy_hms(x) paste0(c(day(y),as.character(month(y, label = T)),year(y)), collapse = "-") # [1] "11-May-2018" paste0(c(as.character(month(y, label = T)),year(y)), collapse = "-") # [1] "May-2018" paste0(c(month(y),year(y)), collapse = "-") # [1] "5-2018" 
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of extracting the information you can also use : format(y, format = "%d-%b-%Y"), format(y, format = "%b-%Y"), format(y, format = "%m-%Y")
2

It should work as well:

str<-"11MAY2018:00:00:00.000" dt<-substring(str, c(1), c( 9)) as.Date(dt,format='%d%b%Y') 

https://www.stat.berkeley.edu/~s133/dates.html

6 Comments

You can use substring(str, 1, 9), without the c(.). But your output seems to be "2020-05-11". It works with as.Date(dt,format='%d%b%Y') (capital Y)
This only works for this one case, but not if you have different months
@AntoniosK i have no idea from where it comes to 2020. Do you have any idea?
Your format specification is not totally correct, %ylooks for only a two-digit year, you need %Y as @AntoniosK already said
@kath i have tried it for "11SEP2018:00:00:00.000", and it works well. So, why do you think, it does not work for different monthes?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.