代码之家  ›  专栏  ›  技术社区  ›  Chang Chung

在R中处理时间的最佳实践是什么?

  •  14
  • Chang Chung  · 技术社区  · 17 年前

    vectors , start finish ,分别表示面试开始和结束的时间。

    他们是 character 如下所示的字符串: "9:24 am" , "12:35 pm"

    我知道,对于约会,有很多 classe function 就像 as.date() , as.Date() chron() as.POSIXct() . 所以我在找类似的东西 as.time() ,但找不到它。我是否应该附加一个虚构的日期,然后将整个事件转换为 POSIX() 日期时间 class difftime() ?

    处理时间的最佳实践是什么 R ?

    3 回复  |  直到 8 年前
        1
  •  15
  •   vrajs5    12 年前

    你需要使用 strptime()

    strptime("9:24 am",format="%I:%M %p")
    

    strptime("9:24 am",format="%I:%M %p")-strptime("12:14 am",format="%I:%M %p")
    Time difference of 9.166667 hours
    

    您可以将其存储起来,然后执行以下操作: as.numeric() 如果您只想输出数字,则可以传递时间对象。

        2
  •  1
  •   Samuel    17 年前

    一种选择是使用正则表达式。如果您不熟悉它们,可以使用它们使用模式解析字符串。我会研究正则表达式,然后 here are the functions in r

    希望能有帮助

        3
  •  0
  •   Ajay Ohri    9 年前

    https://www.rdocumentation.org/packages/lubridate/versions/1.5.6/topics/hm

    hm(c("09:10", "09:02", "1:10"))
    ## [1] "9H 10M 0S" "9H 2M 0S"  "1H 10M 0S
    

    然后在上面创建的日期-时间格式中使用difftime作为差异 https://stat.ethz.ch/R-manual/R-devel/library/base/html/difftime.html

    difftime(time1, time2, tz,
             units = c("auto", "secs", "mins", "hours",
                       "days", "weeks"))