Adding time in milliseconds to Time Stamp in R

Viewed 66

I am having an issue with adding time in ms to a specific time stamp. My data contain two variables, Start Time (Time, in HH:MM:SS.ss format) and time for a specific event given in ms that have passed since the Start Time (STime, numeric variables, i.e. 640654 ms, which equals 640.654 s or 10.678.. min). For example:

Time <- c("16:44:38.00", "16:44:38.00", "16:44:38.00")
STime <- c(640657, 940640, 955301)

Here on the forum I found the code (thank you @tstev) that should allow calculating FTime - Start Time with STime added, and shown in HH:MM:SS.ss format:

FTime <- strftime(strptime(Time,format="%H:%M:%OS")+(STime %% 1)+0.005,format="%H:%M:%OS3")

However, in my case it does not add STime properly - I've tried to present STime in seconds instead of ms (640.657, 940.640, 955.301) and then add - it still does not provide accurate results, here's what I've got:

"16:44:38.662", "16:44:38.645", "16:44:39.306"

Does anyone know how to fix this?

Cheers

1 Answers

You can use the library hms. I divided the microseconds by 1000 to render them as seconds, then converted the values.

library(hms)
library(tidyverse)

Time <- c("16:44:38.00", "16:44:38.00", "16:44:38.00") %>% as_hms()
STime <- (c(640657, 940640, 955301) / 1000) %>% hms(seconds = .)

(Time + STime) %>% as_hms()
# 16:55:18.657
# 17:00:18.640
# 17:00:33.301 

Let me know if you have any questions.

Related