【发布时间】:2021-09-28 06:42:01
【问题描述】:
我正在尝试使用将 POSIX 对象转换为 R 中的字符串
as.character(Sys.time()) 返回"2021-09-28 08:38:13"
但是,如果我只运行Sys.time(),我会得到"2021-09-28 08:38:13 CEST"。
如何将时区信息也转换为字符串?
【问题讨论】:
我正在尝试使用将 POSIX 对象转换为 R 中的字符串
as.character(Sys.time()) 返回"2021-09-28 08:38:13"
但是,如果我只运行Sys.time(),我会得到"2021-09-28 08:38:13 CEST"。
如何将时区信息也转换为字符串?
【问题讨论】:
使用选项usetz = TRUE
as.character(Sys.time(), usetz = TRUE)
【讨论】:
您可以使用format 和'%Z' 来表示时区。
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"
【讨论】:
format 和 usetz = TRUE 可以做同样的事情:
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))。