How to preserve decimal values when converting POSIXct to character?
Asked Answered
B

2

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?

Bonds answered 23/6, 2021 at 12:35 Comment(1)
It is often wise to give your objects not the same name as a function; see ?t.Hamil
A
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
Autoplasty answered 23/6, 2021 at 12:46 Comment(1)
Is there a way to do it without having to mess with the global options?Bonds
G
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
Gallnut answered 23/6, 2021 at 15:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.