Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between dates in R

Tags:

date

datetime

r

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.

like image 404
Aslan Bayramkulov Avatar asked Feb 09 '17 09:02

Aslan Bayramkulov


1 Answers

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"
like image 126
joel.wilson Avatar answered Nov 17 '22 05:11

joel.wilson