1

I am facing an issue, and I suspect it's a bug in POSIXct, or a rounding error, but how to prevent it ?

When the millisecond in datetime is exactly 1 in the following format, the millisecond get skipped (become 0). This does not happen for any other millisecond value.

> as.POSIXct("2023-08-03T14:25:00.001Z" , format = "%Y-%m-%dT%H:%M:%OSZ" , tz = "UTC")
[1] "2023-08-03 14:25:00.000 UTC"

Trying to extend to 6 digits and we also loose the last digit (e-6 seconds)

> as.POSIXct("2023-08-03T14:25:00.001001Z" , format = "%Y-%m-%dT%H:%M:%OSZ" , tz = "UTC") %>% strftime(format = "%Y-%m-%dT%H:%M:%OS6Z")
[1] "2023-08-03T16:25:00.001000Z"

R Version :

platform       x86_64-pc-linux-gnu         
arch           x86_64                      
os             linux-gnu                   
system         x86_64, linux-gnu           
status                                     
major          4                           
minor          3.0                         
year           2023                        
month          04                          
day            21                          
svn rev        84292                       
language       R                           
version.string R version 4.3.0 (2023-04-21)
nickname       Already Tomorrow     
Xavier
  • 31
  • 4
  • 4
    That is a know issue with the available resolution of a POSIXct variable stored in a single double of 64 bit width. You could use `integer64` from the `bit64` package, this is available e.g. in my `nanotime()` package. – Dirk Eddelbuettel Aug 03 '23 at 13:35
  • 1
    For your first example, you can pass it to `|> strftime(format = "%H:%M:%OS6")` and you can see it is parsed as `"14:25:00.000999"` – Darren Tsai Aug 03 '23 at 13:39
  • 3
    Does this answer your question? [Accurately converting from character->POSIXct->character with sub millisecond datetimes](https://stackoverflow.com/questions/15383057/accurately-converting-from-character-posixct-character-with-sub-millisecond-da) See also: https://stackoverflow.com/questions/7726034/how-r-formats-posixct-with-fractional-seconds – Matt Summersgill Aug 03 '23 at 13:40
  • 3
    According to `help("strftime")`: "Specific to R is %OSn, which for output gives the seconds **truncated** to 0 <= n <= 6 decimal places" Floating point numbers are usually not exact. Check out `sprintf("%.20f", unclass(x))`. – Roland Aug 03 '23 at 13:40

0 Answers0