简体   繁体   中英

Parse an incomplete date character column (d-HH:MM:SS) in R. More elegant approach?

Old bit of kit generates a DateTime column in the format of:

"d-HH:MM:SS" eg "26-16:24:40" which should be "2021-11-26 16:24:40"

I am asking if there is a more elegant way to convert this column?

My attempt:

dat %>%
mutate(year = "2021", month = "11") %>%
  mutate(day = substr(date.time, 1, 2), 
         hour = substr(date.time, 4, 5),
         minute = substr(date.time, 7, 8),
         second = substr(date.time, 10, 11)) %>%
  mutate(date = make_datetime(year, month, day, hour, minute, second))

I am curious to see other methods. Some example dates below.

testDate <- c("26-16:24:40", "26-16:29:40", "26-16:34:40", "26-16:39:40", "26-16:44:40", "26-16:49:40", "26-16:54:40", "26-16:59:40", "26-17:04:40", "26-17:09:40")

as.POSIXct(paste0("2021-11-", testDate), format = "%Y-%m-%d-%H:%M:%S")

 [1] "2021-11-26 16:24:40 CET" "2021-11-26 16:29:40 CET" "2021-11-26 16:34:40 CET" "2021-11-26 16:39:40 CET"
 [5] "2021-11-26 16:44:40 CET" "2021-11-26 16:49:40 CET" "2021-11-26 16:54:40 CET" "2021-11-26 16:59:40 CET"
 [9] "2021-11-26 17:04:40 CET" "2021-11-26 17:09:40 CET"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM