【问题标题】:character to time with milliseconds and without date and tz字符到时间,以毫秒为单位,没有日期和 tz
【发布时间】:2019-09-19 06:47:21
【问题描述】:

我有一个像下面这样的字符向量,它以 HH:MM:SS.sss 格式保存时间,以便它可以用于数据帧中的时间序列分析

x <- "05:17:55.703"

我想将它转换为没有日期和时区的毫秒时间戳 - 这甚至可能吗?

我尝试了什么 ->

> as.POSIXct("05:17:55.703",format = "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> as.POSIXlt("05:17:55.703",format = "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> as.POSIXlt("05:17:55.703",format = "%H:%M:%S.%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> strptime("05:17:55.703", "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

【问题讨论】:

  • Datetime 对象必须包含日期。但是,我想知道您为什么关心显示的内容。实际值对您来说应该更重要。

标签: r time


【解决方案1】:

您可以考虑使用来自lubridatehms,这将返回一个"Period" 对象

lubridate::hms(x)
#[1] "5H 17M 55.703S"

这显示没有日期和时区的毫秒部分。

【讨论】:

    【解决方案2】:

    另一个选项是 hms 包:

    hms::as_hms("05:17:55.703")
    #> 05:17:55.703
    

    reprex package (v0.3.0) 于 2019 年 9 月 19 日创建

    【讨论】:

      【解决方案3】:

      您可以使用as.POSIXct("05:17:55.703",format = "%H:%M:%OS")options(digits.sec = 3)。这应该给 "2022-03-28 05:17:55.703 CEST"

      as.POSIXct("05:17:55.703",format = "%H:%M:%OS")
      options(digits.sec = 3)
      #  "2022-03-28 05:17:55.703 CEST"
      

      【讨论】:

        猜你喜欢
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-07
        • 2016-09-06
        • 1970-01-01
        • 1970-01-01
        • 2011-10-07
        相关资源
        最近更新 更多