The difference between dates in 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 the difference between T1 and T2 in this format:

 format = "%H:%M:%OS" 

For example, the difference between certain dates:

 diff = "04:30:15.062262" 

I tried different approaches, but that was unsuccessful.

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 do not know how to get fractional numbers.

+6
source share
1 answer

the code is self-evident

 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" 
+6
source

Source: https://habr.com/ru/post/1014830/


All Articles