使用difftime()时如何提取时间单位?

时间:2019-01-17 02:03:54

标签: r time difftime

我当前正在运行for循环代码,并且在每个循环结束时,我正在测量循环的持续时间,并输出一条消息,告诉用户循环用了多长时间。

要获取我正在使用的持续时间

duration <- difftime(end_time, start_time) 

这就是我打印语句的方式

print(paste("Loop", i, "took", duration, "to run.")). 

问题是每个循环的持续时间可能从30秒到1小时不等。将持续时间放在粘贴中只会将其变成没有单位的数字。

例如

print(paste("Loop", i, "took", duration, "to run.")). 
"Loop 5 took 10.5 to run"

如何从difftime()中获取单位,以获得类似以下内容: “第5圈需要10.5分钟才能运行。”

PS:有些人可能建议通过在difftime()中声明“ unit”参数来标准化持续时间,但是我希望用户容易理解持续时间,这就是为什么将unit设置为默认“ auto”的原因。

3 个答案:

答案 0 :(得分:2)

通过units的子集调用duration中的duration,以获取单位并获取数值:

print(paste("Loop", i, "took", round(duration[[1]], 2),  units(duration), "to run."))

这里是一个例子:

start_time <- Sys.time()

# few seconds later
end_time <- Sys.time()

duration <- difftime(end_time, start_time)

print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))

结果:

[1] "Loop 1 took 6.97 secs to run."

根据持续时间的范围,单位将是自动的。请参阅以下示例:

start_time <- Sys.time()

# few days later
end_time <- as.Date("2019-01-23")

duration <- difftime(end_time, start_time)

print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))

结果:

> print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))
[1] "Loop 1 took 5.9 days to run."

答案 1 :(得分:1)

一种方法是使用difftime捕获capture.output的输出

start_time <- as.POSIXct('2019-01-01 02:34:00')
end_time <- as.POSIXct('2019-01-01 03:14:00')

paste("Loop 5 took", capture.output(difftime(end_time, start_time)), "to run.")
#[1] "Loop 5 took Time difference of 40 mins to run."

现在您可以更改输出以使其有意义,例如说从输出中删除“时差为”

sent <- capture.output(difftime(end_time, start_time))
paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
#[1] "Loop 5 took 40 mins to run."

其他输入

start_time <- as.POSIXct('2019-01-01 02:34:00')
end_time <- as.POSIXct('2019-01-01 02:34:50')

sent <- capture.output(difftime(end_time, start_time))
paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
#[1] "Loop 5 took 50 secs to run."

答案 2 :(得分:0)

您应该可以通过units(duration)来获取。