【问题标题】:Keep time zone information when converting POSIX object to string [duplicate]将POSIX对象转换为字符串时保留时区信息[重复]
【发布时间】: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"

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

【问题讨论】:

    标签: r datetime posix


    【解决方案1】:

    使用选项usetz = TRUE

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          formatusetz = 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 &lt;- 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))
          猜你喜欢
          • 1970-01-01
          • 2017-09-10
          • 1970-01-01
          • 2017-10-07
          • 2016-09-24
          • 2014-06-13
          • 1970-01-01
          • 2017-07-14
          • 1970-01-01
          相关资源
          最近更新 更多