How to create only time in R

Viewed 105

I have a time column in my dataframe, its format is character:

TIME
10:54:10.23
10:54:11.58
10:56:34.21
11:57:11.23

So u see I also have milliseconds in the end, but I try to get only %H-%M-%S without the .x milliseconds. I tried to creat a new column by: data$hms <- format(as.POSIXct(data$TIME), "%H:%M:%S") but failed... Error in as.POSIXlt.character(x, tz, ...): String is not in a unique standard format.

Every help is appreciated.

3 Answers

You can drop the milliseconds from the time.

df <- transform(df, TIME = sub('\\..*', '', TIME))
df
#      TIME
#1 10:54:10
#2 10:54:11
#3 10:56:34
#4 11:57:11

We could use times from chron package after removing the last two digits with str_remove

#install.packages("chron")
library(chron)
library(dplyr)
library(stringr)
df %>% 
    mutate(TIME = chron(times=str_remove(TIME, '\\..*$')))

output:

  TIME    
  <times> 
1 10:54:10
2 10:54:11
3 10:56:34
4 11:57:11

data

df <- structure(list(TIME = c("10:54:10.23", "10:54:11.58", "10:56:34.21", 
                        "11:57:11.23")), class = "data.frame", row.names = c(NA, -4L))

We could use trimws from base R

df$TIME <- trimws(df$TIME, whitespace = "\\.\\d+")

-output

df$TIME
[1] "10:54:10" "10:54:11" "10:56:34" "11:57:11"

data

df <- structure(list(TIME = c("10:54:10.23", "10:54:11.58", "10:56:34.21", 
"11:57:11.23")), class = "data.frame", row.names = c(NA, -4L))
Related