Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make time difference in same units when subtracting POSIXct

Tags:

I want to subtract to POSIXct. I can do this but depending on the first row (i guess?) the difference will be in seconds or minutes. Below you can see the first diff is in seconds and the second diff is in minutes because I changed the time difference in the first row:

#diff in seconds because 1st row time diff is small? t1<- as.POSIXct(c("2015-02-02 20:18:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT") t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT") d<-data.frame(t1= t1, t2= t2) d$t1-d$t2   #diff in seconds because 1st row time diff is larger? t1<- as.POSIXct(c("2015-02-02 20:13:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT") t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT") d<-data.frame(t1= t1, t2= t2) d$t1-d$t2 

results:

> #diff in seconds because 1st row time diff is small? > t1<- as.POSIXct(c("2015-02-02 20:18:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT") > t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT") > d<-data.frame(t1= t1, t2= t2) > d$t1-d$t2 Time differences in secs [1]   1 -60 >  >  > #diff in seconds because 1st row time diff is larger? > t1<- as.POSIXct(c("2015-02-02 20:13:03 00:00:00", "2015-02-02 20:17:02 00:00:00"),"GMT") > t2<- as.POSIXct(c("2015-02-02 20:18:02 00:00:00","2015-02-02 20:18:02 00:00:00"),"GMT") > d<-data.frame(t1= t1, t2= t2) > d$t1-d$t2 Time differences in mins [1] -4.983333 -1.000000 

I would like the difference to ALWAYS be in seconds no matter what the first row difference is. Is there a way to make this happen?

Thank you.

like image 372
user3022875 Avatar asked May 28 '15 14:05

user3022875


People also ask

How do I subtract two timestamps in R?

The difftime() method in R is used to compute the difference in the timestamps given. It is used to return an object of the class difftime itself accompanied by units attribute.

How do you add or subtract time in R?

Method 1: Using POSIXct object A string type date object can be converted to POSIXct object, using them as. POSIXct(date) method in R. Since, the dates are stored in terms of seconds, the subtraction, as well as addition, can be performed by first converting the hours and minutes to the units of seconds too.


1 Answers

You can use difftime for that propose which allows you to specify the measurement units, for example

difftime(t1, t2, units = "secs") 

Another way (as mentioned by @nicola and is present in the same documentation) is to take advantage of the fact that - has a -.POSIXt method and override the measurement units after the subtraction operation using units<- replacement method

res <- t1 - t2 units(res) <- "secs" 
like image 112
David Arenburg Avatar answered Sep 23 '22 14:09

David Arenburg