Search code examples
rdatetimelubridatemilliseconds

R How to convert milliseconds from origin to date and keep the milliseconds


I realize there are several other questions similar to this, but all the answers I have seen suggest dividing a UNIX timestamp in milliseconds by 1000 for R to handle it properly (for example, 1506378449 instead of 1506378448618).

Is there a way to convert it without dividing by 1000 and keep those fractional seconds?

What I have tried so far does not work:

as.POSIXct(1506378448618, origin = "1970-01-01", tz = 
"America/Chicago", format = "%Y-%m-%d %H:%M:%OS") 

comes back NA, and it similarly does so with %OS1, 2, 3, etc.

anytime(1506378448618, tz = "America/Chicago")

and

as_datetime(1506378448618, tz = "America/Chicago")

both come back with times far into the future ("49705-03-26 12:56:58 CDT")

The best answer I can come up with is to split the string and do something like:

as_datetime(1506378448, tz = "America/Chicago") + .618

Which is fine, but it seems like there must be a better way.


Solution

  • I'm not entirely sure what you're asking.

    as.POSIXct(...) does in fact keep track of fractional seconds. You can print fractions of seconds using the appropriate format string.

    For example to print the first 3 digits you can do

    t <- 1506378448618;
    format(as.POSIXct(t / 1000, origin = "1970-01-01", tz = "America/Chicago"), "%H:%M:%OS3")
    #[1] "17:27:28.618"
    

    Note: The reason why as.POSIXct(..., format = "%Y-%m-%d %H:%M:%OS") results in NA is simply because your input object 1506378448618 does not have format "%Y-%m-%d %H:%M:%OS". You can however specify a format string when printing the POSIXct object.