Home > Net >  Change date format with POSIXct when using an own format in r?
Change date format with POSIXct when using an own format in r?

Time:07-18

hey guys i have a date format like this as a string "Wed May 23 22:58:46 0000 2019" and i need to change it into this format "%m/%d/%Y %I:%M:%S

my code looks like this:

x <- "Wed May 01 23:59:45  0000 2019" 

xx <- as.POSIXct(x, format = "%a %b %d %H:%M:%S %z %Y")

but it does not work...

CodePudding user response:

Here is step by step stringr combined with lubridate solution wrapped in a function. In essence we bring the string x with the stringr functions to a form where we could apply lubridates mdy_hms function. Note: This solution is not elegant!

x <- "Wed May 01 23:59:45  0000 2019"


library(lubridate)
library(stringr)
special_datetime_function <- function(x){
  x1 <- str_remove(x, "\\d{2}\\:\\d{2}\\:\\d{2}\\s\\ \\d ")
  x2 <- str_extract(x, "\\d{2}\\:\\d{2}\\:\\d{2}")
  y <- str_c(x1, x2, sep = " ")
  y1 <- str_squish(str_replace(y, "^\\S* ", ""))
  mdy_hms(y1)
}
special_datetime_function(x)
[1] "2019-05-01 23:59:45 UTC"
  •  Tags:  
  • r
  • Related