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

后端 未结 4 449
独厮守ぢ
独厮守ぢ 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条回答
  •  旧时难觅i
    2020-12-03 09:29

    As the answers to the questions you linked to already say, how a value is printed/formatted is not the same as what the actual value is. This is just a printed representation issue.

    R> as.POSIXct('2011-10-11 07:49:36.3')-as.POSIXlt('2011-10-11 07:49:36.3')
    Time difference of 0 secs
    R> as.POSIXct('2011-10-11 07:49:36.2')-as.POSIXlt('2011-10-11 07:49:36.3')
    Time difference of -0.0999999 secs
    

    Your understanding that POSIXct is less precise than POSIXlt is incorrect. You're also incorrect in saying that you can't include a POSIXlt object as a column in a data.frame.

    R> x <- data.frame(date=Sys.time())
    R> x$date <- as.POSIXlt(x$date)
    R> str(x)
    'data.frame':   1 obs. of  1 variable:
     $ date: POSIXlt, format: "2013-03-13 07:38:48"
    

提交回复
热议问题