首页 > 解决方案 > 将持续时间转换为 ISO 8601 格式

问题描述

是否有将持续时间(来自 lubridate::duration 的输出)转换为 ISO8601 持续时间格式的功能?例如

lubridate::duration("PT1H3M")
# "3780s (~1.05 hours)"

但我将如何得到相反的结果?例如输入是

"3780s (~1.05 hours)"

要得到:

"PT1H3M"

参考:ISO8601 持续时间:

https://www.digi.com/resources/documentation/digidocs/90001437-13/reference/r_iso_8601_duration_format.htm

标签: r

解决方案


中的函数适用format_ISO8601()lubridate日期和持续时间:

my_duration <- lubridate::duration("PT1H3M")

my_duration

# [1] "3780s (~1.05 hours)"


lubridate::format_ISO8601(my_duration)

# [1] "PT3780S"

但请注意,基础格式不是字符串(正如您的问题可能暗示的那样):

str(my_duration)

# Formal class 'Duration' [package "lubridate"] with 1 slot
#   ..@ .Data: num 3780

lubridate::format_ISO8601("3780s (~1.05 hours)")

# Error in (function (classes, fdef, mtable)  :
  # unable to find an inherited method for function ‘format_ISO8601’ for signature ‘&quot;character"’

推荐阅读