I have a problem with dates in R. Define T1 and T2 as dates in POSIXct or POSIXlt format with 6 fractional seconds:
op <- options(digits.secs = 6)
T1 = strptime("2015.10.10 12:00:00.150150", "%Y.%m.%d %H:%M:%OS")
T2 = strptime("2015.10.10 16:30:15.212412", "%Y.%m.%d %H:%M:%OS")
How to get difference between T1 and T2 in this format:
format = "%H:%M:%OS"
For example difference between defined dates is:
diff = "04:30:15.062262"
I tried different approaches, but it wasn't successful.
My attempts:
T1 = strptime("2015.10.10 12:00:00.150150", "%Y.%m.%d %H:%M:%OS")
T2 = strptime("2015.10.10 16:30:15.212412", "%Y.%m.%d %H:%M:%OS")
h = difftime(T2,T1, units = "hours")
m = difftime(T2,T1, units = "mins")
s = difftime(T2,T1, units = "secs")
But I don't know how to get fractionals.
the code is self-explainable
x <- as.numeric(difftime(T2,T1,units = "sec")) # diff in sec
hrs <- floor(x/3600) # get the hours
x <- x%%3600 # update the x after removing the hrs(in sec)
min <- floor(x/60) # get the minutes
sec <- x%%60 # get the sec
paste(hrs,min,sec,sep= ":")
# [1] "4:30:15.0622620582581"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With