I have tried to get just the current miliseconds from the current second in R with the following code:
options("digits.secs" = 6) # since 6 is the maximum digits for seconds apparently
Sys.time()
So, it returns the full date with the miliseconds.
2024-10-09 14:35:51.687084 CEST
But if i just want to have the miliseconds what should i do with format()
?
I have tried,
options(digits.secs = 6)
format(Sys.time(), "%X")
But it only returns the following:
14:35:51
I just want it to return 687084
I know i can do the following but it does not look optimal:
options("digits.secs" = 6)
unlist(strsplit(x = as.character(Sys.time()), split = "\\."))[2]
Do you have any idea how to do it?
Thanks.
No format will give the seconds' decimal part, you have to extract from the value representing a date/time. In R, objects of class "POSIXct"
are represented as numbers.
Two ways.
substring
to extract the decimal digits as characters;secs_decimal1 <- function(x) {
if(missing(x)) x <- Sys.time()
substring(x, 21L)
}
secs_decimal2 <- function(x) {
if(missing(x)) x <- Sys.time()
unclass(x) %% 1L
}
# save the current setting
op <- options("digits.secs" = 6)
x <- Sys.time()
secs_decimal1(x)
#> [1] "344074"
secs_decimal2(x)
#> [1] 0.344074
options(op)
Created on 2024-10-09 with reprex v2.1.0