Accurately converting from character->POSIXct->character with sub millisecond datetimes

后端 未结 4 442
独厮守ぢ
独厮守ぢ 2020-12-03 08:51

I have a character datetime column in a file. I load the file (into a data.table) and do things that require the column to be converted to POSIXct.

4条回答
  •  伪装坚强ぢ
    2020-12-03 09:39

    When you write

    My understanding is that POSIXct representation is less precise than the POSIXlt representation

    you are plain wrong.

    It is the same representation for both -- down to milliseconds on Windows, and down to (almost) microseconds on the other OSs. Did you read help(DateTimeClasses) ?

    As for your last question, yes the development version of my RcppBDT package uses Boost Date.Time and can go all the way to nanoseconds if your OS supports it and you turned the proper representation on. But it does replace POSIXct, and does not yet support vectors of time objects.

    Edit: Regarding your follow-up question:

    R> one <- Sys.time(); two <- Sys.time(); two - one
    Time difference of 7.43866e-05 secs
    R>
    R> as.POSIXlt(two) - as.POSIXlt(one)
    Time difference of 7.43866e-05 secs
    R> 
    R> one    # options("digits.sec"=6) on my box
    [1] "2013-03-13 07:30:57.757937 CDT"
    R> 
    

    Edit 2: I think you are simply experiencing that floating point representation on computers is inexact:

    R> print(as.numeric(as.POSIXct("04-Jan-2013 17:22:08.138",
    +                   format="%d-%b-%Y %H:%M:%OS")), digits=18)
    [1] 1357341728.13800001
    R> print(as.numeric(as.POSIXct("04-Jan-2013 17:22:08.139",
    +                   format="%d-%b-%Y %H:%M:%OS")), digits=18)
    [1] 1357341728.13899994
    R> 
    

    The difference is not precisely 1/1000 as you assumed.

提交回复
热议问题