减去POSIXct时如何使相同单位的时间差

How to make time difference in same units when subtracting POSIXct

我想减去POSIXct。我可以做到这一点,但取决于第一行(我猜?),差异将以秒或分钟为单位。下面你可以看到第一个差异以秒为单位,第二个差异以分钟为单位,因为我更改了第一行的时差:

#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

结果:

> #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

无论第一行的差异是多少,我都希望差异始终以秒为单位。有办法实现吗?

谢谢。

您可以使用 difftime 来指定测量单位,例如

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

另一种方法(如@nicola 所述并出现在同一文档中)是利用 - 具有 -.POSIXt 方法这一事实并在减法后覆盖测量单位使用 units<- 替换方法的操作

res <- t1 - t2
units(res) <- "secs"