5
> t <- Sys.time()
> ct <- as.character(t)
> t - as.POSIXct(ct)
Time difference of 0.4370408 secs

The above example indicates that precision is lost when converting POSIXct to character.

How to preserve the exact value when converting to character so that when I convert back to POSIXct from character I get the original value?

2 Answers2

4

You can set the option digits.secs to 6 (its maximum value).

options(digits.secs = 6)

t <- Sys.time()
ct <- as.character(t)
t - as.POSIXct(ct)
Time difference of 0 secs
ktiu
  • 2,606
  • 6
  • 20
2

You can use format with %OS6, to give seconds in digits, but still there will be sometimes a difference:

t <- Sys.time()
ct <- format(t, "%Y-%m-%d %H:%M:%OS6")
t - as.POSIXct(ct)
#Time difference of 0 secs
GKi
  • 37,245
  • 2
  • 26
  • 48