1

I am a bit confused by how the function as.POSIXct() handles milliseconds. Reproducible code with R v4.0.5 is shown below (fresh session, no packages loaded).

> options("digits.secs" = 3)

> a <- as.POSIXct("2020-09-14 00:01:39.800")
> a
[1] "2020-09-14 00:01:39.7 CEST"
> format(a, "%Y-%m-%d  %H:%M:%OS3")
[1] "2020-09-14  00:01:39.799"

> b <- as.POSIXlt("2020-09-14 00:01:39.800")
> b
[1] "2020-09-14 00:01:39.8 CEST"
> format(b, "%Y-%m-%d  %H:%M:%OS3")
[1] "2020-09-14  00:01:39.800"

Can anyone shed some light on this behavior? Why does as.POSIXct change my .800 ms to .799 ms? I never noticed. Can this be a bug introduced in recent R versions?

DanVal80
  • 11
  • 2
  • it could be a difference in how the methods handle rounding... one truncates, the other rounds up. try looking at sprintf("%.20f", as.numeric(a)) – MichaelChirico Apr 12 '21 at 16:32
  • `> sprintf("%.20f", as.numeric(a))` `[1] "1600034499.79999995231628417969"` – DanVal80 Apr 12 '21 at 16:38
  • 1
    Thank you. I understand that internally as.POSIXct(date)==as.POSIXlt(date). I also found this other post explaining the situation much better than I could do (and in my opinion more thoroughly than the linked answer): https://stackoverflow.com/questions/7726034/how-r-formats-posixct-with-fractional-seconds – DanVal80 Apr 12 '21 at 18:34

0 Answers0