I'm trying to convert a POSIX object to a string in R by using
as.character(Sys.time())
which returns "2021-09-28 08:38:13"
However, if I just run Sys.time()
I get "2021-09-28 08:38:13 CEST"
.
How do I get the time zone information to be converted to the string, too?
CodePudding user response:
use option usetz = TRUE
as.character(Sys.time(), usetz = TRUE)
CodePudding user response:
You can use format
with '%Z'
to denote timezone.
format(Sys.time(), '%Y-%m-%d %T %Z')
CodePudding user response:
Using strftime(
.
strftime(Sys.time(), '%c')
# [1] "Tue 28 Sep 2021 08:43:06 CEST"
or
strftime(Sys.time(), '%F %X %Z')
# [1] "2021-09-28 08:45:42 CEST"
CodePudding user response:
The same thing could be done with format
with usetz = TRUE
:
format(Sys.time(), usetz = TRUE)
Output:
2021-09-28 08:38:13 CEST
Timings:
a <- proc.time()
for (i in 1:100000)
{
format(Sys.time(), usetz = TRUE)
}
print(proc.time() - a)
b <- proc.time()
for (i in 1:100000)
{
as.character(Sys.time(), usetz = TRUE)
}
print(proc.time() - b)
format
(mine) is quicker than as.character
(Park's answer). The output is:
user system elapsed
11.040 0.520 11.563
user system elapsed
11.930 0.290 12.229
The second one is Park's.