我正在尝试使用 as.character(Sys.time())
将POSIX对象转换为R中的字符串,它返回"2021-09-28 08:38:13"
。
但是,如果我只运行Sys.time()
,我会得到"2021-09-28 08:38:13 CEST"
。
我该如何将时区信息也转换为字符串?
使用选项 usetz = TRUE
as.character(Sys.time(), usetz = TRUE)
您可以使用'%Z'
和format
结合使用来表示时区。
format(Sys.time(), '%Y-%m-%d %T %Z')
使用 strftime()
函数。
strftime(Sys.time(), '%c')
# [1] "Tue 28 Sep 2021 08:43:06 CEST"
strftime(Sys.time(), '%F %X %Z')
# [1] "2021-09-28 08:45:42 CEST"
usetz = TRUE
来使用format
函数完成:format(Sys.time(), usetz = TRUE)
输出:
2021-09-28 08:38:13 CEST
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
(我的回答)比as.character
(Park的回答)更快。输出结果如下:
user system elapsed
11.040 0.520 11.563
user system elapsed
11.930 0.290 12.229
x <- rep(Sys.time(), 1e4); microbenchmark::microbenchmark(as.character=as.character(x, usetz = TRUE), format=format(x, '%Y-%m-%d %T %Z'), strftime=strftime(x, '%F %X %Z'),format2=format(x, usetz = TRUE))
。 - jay.sf