【问题标题】:How to elegantly convert datetime from decimal to "%d.%m.%y %H:%M:%S"?如何优雅地将日期时间从十进制转换为“%d.%m.%y %H:%M:%S”?
【发布时间】:2012-08-28 14:52:56
【问题描述】:

我正在做一个产生自动记录数据的实验。该软件会生成格式为41149.014850 的时间戳。我想将此十进制时间戳转换为28.08.2012 00:21:23。我怎样才能最优雅地在 R 中做到这一点?

我尝试使用函数 strsplit 以及指定原点的函数 as.Date 以及 times 函数。但无济于事。我在将时间戳分成两个数字时遇到问题,我可以使用函数 as.Datetimes 访问它们。

这是一些演示代码:

myDatetime <- c(41149.004641, # 28.08.2012  00:06:41
41149.009745, # 28.08.2012  00:14:02
41149.014850, # 28.08.2012  00:21:23
41149.019954) # 28.08.2012  00:28:44

## not working out for me
Dat.char <- as.character(myDatetime)
date.split <- strsplit(Dat.char, split = "\\.")
## how to proceed from here, if it is a good way at all

【问题讨论】:

    标签: r date split


    【解决方案1】:

    您的日期采用类似于 Excel 的日期格式(1900 年 1 月 1 日之后的几天),因此您需要将它们转换为 R 日期格式。然后您可以将其转换为日期时间格式 (POSIXct)。

    # first convert to R Date
    datetime <- as.Date(myDatetime-1, origin="1899-12-31")
    # now convert to POSIXct
    (posixct <- .POSIXct(unclass(datetime)*86400, tz="GMT"))
    # [1] "2012-08-28 00:06:40 GMT" "2012-08-28 00:14:01 GMT"
    # [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT"
    # times are sometimes off by 1 second, add more digits to seconds to see why
    options(digits.secs=6)
    posixct
    # [1] "2012-08-28 00:06:40.9823 GMT" "2012-08-28 00:14:01.9680 GMT"
    # [3] "2012-08-28 00:21:23.0399 GMT" "2012-08-28 00:28:44.0256 GMT"
    # round to nearest second
    (posixct <- round(posixct, "sec"))
    # [1] "2012-08-28 00:06:41 GMT" "2012-08-28 00:14:02 GMT"
    # [3] "2012-08-28 00:21:23 GMT" "2012-08-28 00:28:44 GMT"
    # now you can convert to your desired format
    format(posixct, "%d.%m.%Y %H:%M:%S")
    # [1] "28.08.2012 00:06:41" "28.08.2012 00:14:02"
    # [3] "28.08.2012 00:21:23" "28.08.2012 00:28:44"
    

    【讨论】:

      【解决方案2】:

      这很接近:数字表示自 1900 年 1 月 1 日以来的秒数:

      as.POSIXct(x*3600*24, origin=as.Date("1900-01-01")-2, tz="UTC")
      [1] "2012-08-28 01:06:40 BST" "2012-08-28 01:14:01 BST" "2012-08-28 01:21:23 BST"
      [4] "2012-08-28 01:28:44 BST"
      

      那里仍然存在时区偏移。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-28
        • 2020-05-09
        • 2021-11-26
        • 2017-11-02
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多