Insert colons into time stamp hhmmss

1.1k views Asked by At

i am new to stackoverflow and R programming.

Suppose i have the following data:

time<-as.factor(c(142250,101449,85829))
as.data.frame(time)

This will return the following:

    time
  1 142250
  2 101449
  3  85829

What i want is to convert the above into time stamps with a semicolon for example:

142250 will be 14:22:50

i was able to find the following code using the chron package:

library('chron')
times(gsub("(..)(..)(..)", "\\1:\\2:\\3", date))

which returns

[1] 14:22:50 10:14:49 **<NA>**  

As you can see the problem is if there are less than 6 characters it will return an NA.

The output i am after is to return the following results:

[1] 14:22:50 10:14:49 8:58:29  

I believe i may have to do some sort of looping but i am not sure how to go about it?

Any help will be much appreciated.

2

There are 2 answers

1
David Arenburg On BEST ANSWER

So in order to reach your desired output you could use sprintf and add a leading 0 in case the string is shorter than 6, though see @Rolands comment and please provide more clarity

library('chron')
time <- sprintf("%06d", as.numeric(as.character(time)))
times(gsub("(..)(..)(..)", "\\1:\\2:\\3", time))
## [1] 14:22:50 10:14:49 08:58:29
0
Richie Cotton On

I'd be tempted to avoid regular expressions and simply use substring.

time <- sprintf("%06d", as.numeric(as.character(time)))
paste(
  substring(time, 1, 2), 
  substring(time, 3, 4), 
  substring(time, 5, 6), 
  sep = ":"
)