rdatetimetimetimedeltachron

How to format the times and get a time delta in R using chron


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.


Solution

  • 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")