I have two time points, I would like to obtain a time delta (notice that my times have milliseconds). I have tried to use the Chron package :
library(chron)
t1<- '2022/06/28 - 10:45:40:124'
t2<-'2022/06/28 - 10:54:50:193'
chron(t1, format='%Y/%m/%d - %H:%M:%S:%f')
But I got the following error:
Error in parse.format(format): unrecognized format %Y/%m/%d - %H:%M:%S:%f
Traceback:
1. chron("2022/06/28 - 10:45:40:124", format = "%Y/%m/%d - %H:%M:%S:%f")
2. convert.dates(dates., format = fmt, origin. = origin.)
3. parse.format(format)
4. stop(paste("unrecognized format", format))
What is wrong with my implementation?
Thank you for your answers.
CodePudding user response:
Use as.chron
and fix the format.
fmt <- '%Y/%m/%d - %H:%M:%S:%OS'
t1c <- as.chron(t1, format = fmt)
t2c <- as.chron(t2, format = fmt)
# use any of these depending on what you want
t2c - t1c
difftime(t2c, t1c, units = "days")
difftime(t2c, t1c, units = "hours")
difftime(t2c, t1c, units = "mins")
difftime(t2c, t1c, units = "secs")
CodePudding user response:
We may use parse_date
from parsedate
library(parsedate)
parse_date(t1) - parse_date(t2)
Time difference of -9.166667 mins
Or using chron
library(chron)
t1new <- sub(":(\\d )$", ".\\1", trimws(t1, whitespace = ".*-\\s*"))
t2new <- sub(":(\\d )$", ".\\1", trimws(t2, whitespace = ".*-\\s*"))
chron(times = t2new, format = c(times = "h:m:s")) -
chron(times = t1new, format = c(times = "h:m:s"))
[1] 00:09:10