【问题标题】:How to convert 09:35:36 from integer to time format?如何将 09:35:36 从整数转换为时间格式?
【发布时间】:2019-09-13 13:18:20
【问题描述】:

我有以下数据。 order.time 是整数格式。如何在不添加日期的情况下将其转换为时间格式?

order.time
9:58:58
9:58:26
9:56:28
9:56:18
9:56:12

我尝试过使用parse_date_timestrptime,但所有函数都在最终数据中添加了日期和时区。我只想将时间从整数格式转换为可以在 x 轴上绘制时间图的格式

【问题讨论】:

  • 你能提供更多信息吗
  • Base R 有一个日期/时间对象,但没有时间对象。您将需要使用 chron 之类的包,或格式化日期/时间对象以仅在轴上显示时间部分。

标签: r


【解决方案1】:

在 tidyverse 中,hms 包为一天中的时间提供了一个 S3 类:

> time <- hms::as_hms(c("9:58:58", "9:58:26", "9:56:28", "9:56:18", "9:56:12"))
> time
09:58:58
09:58:26
09:56:28
09:56:18
09:56:12
> class(time)
[1] "hms"      "difftime"
> str(time)
 'hms' num [1:5] 09:58:58 09:58:26 09:56:28 09:56:18 ...
 - attr(*, "units")= chr "secs"

函数as_hms() 也接受整数参数,但仅以秒为单位:

> (time_in_hours <- c(6, 9, 12))
[1]  6  9 12
> hms::as_hms(time_in_hours * 3600)
06:00:00
09:00:00
12:00:00

【讨论】:

    【解决方案2】:

    使用as.POSIXct()

    times <- as.POSIXct(c('9:58:58', 9:58:26), format = '%H:%M:%S')
    

    然后你将有一个时间对象,即:times[2] - times[1] 会给你:-32 秒的时间差异。

    您可以按原样绘制它们,也可以使用format(x, format) 对其进行格式化。

    例如:format(times[1], format = '%H:%M:%S') 会给你'09:58:58'。

    【讨论】:

      【解决方案3】:

      我会查看anytime 包。它几乎一直有效。

      library(anytime)
      
      order.time <- anytime(order.time)
      

      【讨论】:

        猜你喜欢
        • 2021-11-14
        • 1970-01-01
        • 2022-12-22
        • 2011-05-30
        • 2023-04-08
        • 2019-11-06
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多