Search code examples
rlubridate

Rounding miliseconds


I'm unsuccessfully trying to round my time column from showing miliseconds to just showing hms I have tried to make it work with floor_date() and round_date() but without any luck. Anyone knows how to round my miliseconds to whole seconds?

All help is much appreciated!

df <- structure(list(date = c("2020-12-15", "2020-12-15", "2020-12-15"
), time = c("09:19:26.599", "09:19:30.391", "09:19:31.142")), row.names = c(NA, 
-3L), class = "data.frame")

Solution

  • You could do this in base R with as.POSIXct

    transform(df, datetime = round(as.POSIXct(paste(date, time), tz = 'UTC')))
    
    #        date         time            datetime
    #1 2020-12-15 09:19:26.599 2020-12-15 09:19:27
    #2 2020-12-15 09:19:30.391 2020-12-15 09:19:30
    #3 2020-12-15 09:19:31.142 2020-12-15 09:19:31
    

    Using dplyr and lubridate :

    library(dplyr)
    df %>% mutate(datetime = round(lubridate::ymd_hms(paste(date, time))))