Milliseconds in POSIXct Class

前端 未结 1 664
你的背包
你的背包 2020-12-09 09:52

How can I parse milliseconds correctly?

as.POSIXct function works as following in my environment.

> as.POSIXct(\"2014-02-24 11:30:00.001\")
[         


        
相关标签:
1条回答
  • 2020-12-09 10:21

    Specify the input format, using %OS to represent the seconds with their fractional parts.

    x <- c("2014-02-24 11:30:00.123", "2014-02-24 11:30:00.456")
    y <- as.POSIXct(x, format = "%Y-%m-%d %H:%M:%OS")
    

    When you come to display the value, append a number between 0 and 6 to the format string to tell R how many decimal places of seconds to display.

    format(y, "%Y-%m-%d %H:%M:%OS6")
    ## [1] "2014-02-24 11:30:00.122999" "2014-02-24 11:30:00.456000"
    

    (Note that you get rounding errors, and R's datetime formatting always rounds downwards, so if you show less decimal places it sometimes looks like you've lost a millisecond.)

    Datetime formats are documented on the ?strptime help page. The relevant paragraph is:

     Specific to R is '%OSn', which for output gives the seconds
     truncated to '0 <= n <= 6' decimal places (and if '%OS' is not
     followed by a digit, it uses the setting of
     'getOption("digits.secs")', or if that is unset, 'n = 3').
     Further, for 'strptime' '%OS' will input seconds including
     fractional seconds.  Note that '%S' ignores (and not rounds)
     fractional parts on output.
    
    0 讨论(0)
提交回复
热议问题