[英]Find difference between times in R
Help me to find difference between times.For eg: these are the date and time 帮助我找出时间之间的时差。例如:这些是日期和时间
2015-11-24 16:49:14
2014-12-02 16:52:43
Need the result in HH:MM:SS
format using r. 需要使用r的HH:MM:SS
格式的结果。
As you need difference between only the time, ignoring the dates you can first extract the time using strptime
由于您只需要时间之间的差异,因此可以忽略日期,首先可以使用strptime
提取时间
x <- strptime(substr(a, 12, 19), format="%H:%M:%S")
y <- strptime(substr(b, 12, 19), format="%H:%M:%S")
Then using the seconds_to_period
function of lubridate
package you can get the time difference and then format the output using sprintf
然后使用seconds_to_period
的功能lubridate
包,你可以得到的时间差,然后使用格式化输出sprintf
library(lubridate)
temp <- seconds_to_period(as.numeric(difftime(y, x, units = "secs")))
sprintf('%02d:%02d:%02d', hour(temp), minute(temp), second(temp))
# [1] "00:03:29"
data 数据
a <- as.POSIXct("2015-11-24 16:49:14")
b <- as.POSIXct("2014-12-02 16:52:43")
Following code to get the difference 遵循代码以获取差异
library(lubridate)
interval(ymd_hms("2015-11-2416:17:38"),ymd_hms("2015-11-24 14:19:44"))
span<-interval(as.POSIXct("2015-11-24 16:17:38"),
as.POSIXct("2015-11-24 14:19:44"))
as.period(span)
Format of answer 答案格式
> -1H -57M -54S
Also display the difference in year, month & date 同时显示年,月和日期的差异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.