You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用lubridate从datetime中提取HH:MM:SS及HH:MM格式时间分量

实现代码(基于你提供的示例继续编写)

你可以直接用format()配合lubridate生成的datetime对象提取指定格式的时间分量,需要可运算的时间类型时可以搭配lubridate内置的类型转换函数:

library(lubridate)
library(dplyr)

# 你原有示例代码
readings <- ymd_hms(c("2018-01-05 12:00:15", "2018-01-01 02:00:15", "2018-02-25 12:00:15", 
                  "2018-04-15 11:00:15", "2020-10-15 10:00:15", "2019-10-20 08:00:15",
                  "2019-11-15 02:01:15", "2018-11-02 11:00:15", "2018-07-09 02:00:15",
                  "2020-10-02 01:00:45", "2020-01-29 02:00:55", "2019-03-15 07:00:15")
)
tbl <- tibble(readings)

# 新增提取时间分量的代码
tbl <- tbl %>%
  mutate(
    # 提取HH:MM:SS格式字符串,可直接用于展示、分组统计
    hms_str = format(readings, "%H:%M:%S"),
    # 提取可参与时间运算的HH:MM:SS时间类型,兼容lubridate运算规则
    hms = hms::as_hms(readings),
    # 提取HH:MM格式字符串
    hm_str = format(readings, "%H:%M"),
    # 提取可参与时间运算的HH:MM周期类型,属于lubridate内置period类
    hm = hm(hm_str)
  )

格式说明

  • format函数中的占位符%H对应24小时制小时、%M对应分钟、%S对应秒,可按需组合得到不同时间格式
  • 可运算的时间类型支持直接做时间差计算、时间偏移等操作,例如用hms - hms("00:00:00")可以直接得到对应的秒数差值

内容的提问来源于stack exchange,提问作者SiH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:24:04