【问题标题】:Format the output of as.period() from lubridate格式化来自 lubridate 的 as.period() 的输出
【发布时间】:2019-10-02 22:02:20
【问题描述】:

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

"35d 17H 15M 28.9999999995343S"

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

35 days 17 hours 15 minutes 28 seconds

我还希望能够对其进行格式化,以便单位采用“s”或不采用“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

有人有线索吗?谢谢。

【问题讨论】:

  • 可能不是最好的方法,但也许“只是”做一个regex 替换?
  • 谢谢。我认为这是可能的,但有点乏味,但我可能会尝试一下。再次感谢您!

标签: r time translation lubridate


【解决方案1】:

一种方法来秒:

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

【讨论】:

  • 非常感谢,它比我使用 seconds() 执行此操作时更简单/更快。你知道为什么秒不是属性的一部分,而是所有其他单位吗?
【解决方案2】:

秒数包含在.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 创建

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2023-02-22
    相关资源
    最近更新 更多