R中日期之间的差异

时间:2017-02-09 09:19:01

标签: r date datetime

我在R中的日期有问题。将T1和T2定义为POSIXct或POSIXlt格式的日期,时间为6小时:

 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")

如何以这种格式区分T1和T2:

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

例如,定义日期之间的差异是:

diff = "04:30:15.062262"

我尝试了不同的方法,但它并没有成功。

我的尝试:

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")

但我不知道如何获得分数。

1 个答案:

答案 0 :(得分:6)

代码是可自我解释的

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"