从 lubridate 格式化 as.period() 的输出

Format the output of as.period() from lubridate

我目前有一个具有此值的期间对象:

"35d 17H 15M 28.9999999995343S"

我想得到一个不同的输出:

35 days 17 hours 15 minutes 28 seconds

我还希望能够对其进行格式化,以便单位采用 "s" 或不采用,具体取决于时间单位是否 > 1。

我已经尝试使用 attr(period_object, "unit") 获取对象的属性,但我无法修改 seconds,因为它们似乎不在对象中。

str(as.period(period_object))
Formal class 'Period' [package "lubridate"] with 6 slots
  ..@ .Data : num 29
  ..@ year  : num 0
  ..@ month : num 0
  ..@ day   : num 35
  ..@ hour  : num 17
  ..@ minute: num 15

这是一个数据样本:

library(lubridate)
time1 <- as.POSIXct("2019-01-01 15:12:07")
time2 <- as.POSIXct("2019-02-06 08:27:36")
period_object <- difftime(time2, time1)

as.period(period_object)
[1] "35d 17H 15M 28.9999999995343S"

所以我想要的最终输出是: 35 days 17 hours 15 minutes 28 seconds

有人知道一些线索吗?谢谢。

秒数的一种方式:

period_object %/% dseconds(1) %% 60
#[1] 28

以这种方式获得它们:

days    <- period_object %/% ddays(1)
hours   <- period_object %/% dhours(1) %% 24
minutes <- period_object %/% dminutes(1) %% 60
seconds <- period_object %/% dseconds(1) %% 60

秒包含在 .Data 槽中。除了秒之外,时间单位在添加到日期时间之前没有固定长度(请参阅 https://lubridate.tidyverse.org/reference/period.html)。秒可以表示为小数,因此可以四舍五入。

您遇到的部分问题是使用 difftime 而不是 lubridate::interval 函数来计算时差。

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

time1 <- as.POSIXct("2019-01-01 15:12:07")
time2 <- as.POSIXct("2019-02-06 08:27:36")
difftime_object <- difftime(time2, time1)
interval_object <- interval(time1, time2)

as.period(difftime_object)
#> [1] "35d 17H 15M 28.9999999995343S"
round(as.period(difftime_object))
#> [1] "35d 17H 15M 29S"

as.period(interval_object)
#> [1] "1m 4d 17H 15M 29S"
as.period(interval_object, unit = "days")
#> [1] "35d 17H 15M 29S"


format_period <- function(x) {
  paste(x@day, "days", x@hour, "hours", x@minute, "minuets", x@.Data, "seconds", sep = " ")
  # or paste(day(x), "days", hour(x), "hours", minute(x), "minuets", second(x), "seconds", sep = " ")
}

format_period(as.period(interval_object, unit = "days"))
#> [1] "35 days 17 hours 15 minuets 29 seconds"

reprex package (v2.0.1)

于 2021-12-06 创建