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

计算hms格式检测时间与darkest.hour的最小时间差(小时制带小数)

计算24小时环形内的最小时间差(hms类型)

已知数据中detection.time和darkest.hour为hms类型,需计算两者在忽略日期情况下的最小时间差(即环形24小时内的最短间隔),并转换为带4位小数的小时单位,可通过以下步骤实现:

实现思路

  1. 将hms类型的时间转换为秒数,便于数值计算;
  2. 计算两个时间点的绝对秒差,再计算24小时(86400秒)与该差值的差,取两者中的较小值,即为环形内的最短时间差;
  3. 将最短秒差转换为小时(除以3600),保留4位小数得到结果。

R代码实现

library(hms)
library(dplyr)

# 示例数据
df <- tibble(
  detection.time = hms::as_hms(c("15:41:00", "14:35:00", "10:45:00", "07:36:00", "23:20:50")),
  darkest.hour = hms::as_hms(rep("01:20:50", 5))
)

# 计算最小时间差
df <- df %>%
  mutate(
    # 转换为秒数
    det_sec = as.numeric(detection.time),
    dark_sec = as.numeric(darkest.hour),
    # 计算环形24小时内的最短秒差
    min_diff_sec = pmin(abs(det_sec - dark_sec), 86400 - abs(det_sec - dark_sec)),
    # 转换为带4位小数的小时
    output = round(min_diff_sec / 3600, 4)
  ) %>%
  # 保留目标列
  select(detection.time, darkest.hour, output)

# 查看结果
print(df, n = 5)

输出结果

运行代码后将得到与期望完全匹配的输出:

# A tibble: 5 × 3
  detection.time darkest.hour output
  <time>         <time>        <dbl>
1 15:41:00       01:20:50      9.6639
2 14:35:00       01:20:50     10.7639
3 10:45:00       01:20:50      9.4028
4 07:36:00       01:20:50      6.2528
5 23:20:50       01:20:50      2.0000

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:06:29