How to elegantly convert datetime from decimal to “%d.%m.%y %H:%M:%S”?

后端 未结 2 1889
你的背包
你的背包 2021-01-18 03:28

I am doing an experiment which produces automatically logged data. The software produces a timestamp that is of the format 41149.014850. I would like to convert

2条回答
  •  -上瘾入骨i
    2021-01-18 04:19

    You dates are in an Excel-like date format (days after January 1, 1900), so you need to convert them to an R date format. Then you can convert it to a datetime format (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"
    

提交回复
热议问题