How to add seconds to time column

715 Views Asked by At

I have a "Time" column in R with a set of character time values in HH:MM:SS However, some of the times do not have the seconds, which makes conversion from char to chron() impossible

Example:

library(chron)

x <- c("08:25:18","08:25","08:24:57","08:24:47")

I want to convert x to chron(), but without the seconds it converts that value to N/A

How can I add :00 seconds to just those that need it? Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

We could convert to date time, format it and then apply the times

library(chron)
library(lubridate)
out1 <- times(format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))
str(out1)
#'times' num [1:4] 08:25:18 08:25:00 08:24:57 08:24:47
# - attr(*, "format")= chr "h:m:s"

Or specify the times in chron

chron(times = format(parse_date_time(x, c('HMS', 'HM')), "%H:%M:%S"))

Or use as.ITime from data.table which would work

library(data.table)
as.ITime(x)
#[1] "08:25:18" "08:25:00" "08:24:57" "08:24:47"