将POSIX对象转换为字符串时保留时区信息。

4

我正在尝试使用 as.character(Sys.time()) 将POSIX对象转换为R中的字符串,它返回"2021-09-28 08:38:13"

但是,如果我只运行Sys.time(),我会得到"2021-09-28 08:38:13 CEST"

我该如何将时区信息也转换为字符串?

4个回答

11

使用选项 usetz = TRUE

as.character(Sys.time(), usetz = TRUE)

5

您可以使用'%Z'format结合使用来表示时区。

format(Sys.time(), '%Y-%m-%d %T %Z')

4

使用 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"

3
同样的事情也可以使用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接