在R中将unix时间戳矩阵转换为人类时间

时间:2018-02-20 10:11:19

标签: r timestamp unix-timestamp timestamp-with-timezone

我有一个人类时代的14 x 2矩阵,称为TH,作为R代码的输出;但是,TH的输出如下:

 [1] "2018-01-24 00:00:00 CET" "2018-01-24 00:24:34 CET" "2018-01-24 08:32:22 CET"
 [4] "2018-01-24 08:42:12 CET" "2018-01-24 09:08:24 CET" "2018-01-24 11:41:36 CET"
 [7] "2018-01-24 12:29:15 CET" "2018-01-24 12:31:47 CET" "2018-01-24 12:33:28 CET"
[10] "2018-01-24 14:32:03 CET" "2018-01-24 15:37:48 CET" "2018-01-24 16:53:36 CET"
[13] "2018-01-24 17:07:18 CET" "2018-01-24 21:10:23 CET" "2018-01-24 00:24:27 CET"
[16] "2018-01-24 08:32:15 CET" "2018-01-24 08:42:05 CET" "2018-01-24 09:08:13 CET"
[19] "2018-01-24 11:41:24 CET" "2018-01-24 12:29:08 CET" "2018-01-24 12:31:41 CET"
[22] "2018-01-24 12:33:11 CET" "2018-01-24 14:31:40 CET" "2018-01-24 15:37:25 CET"
[25] "2018-01-24 16:53:29 CET" "2018-01-24 17:07:11 CET" "2018-01-24 21:10:05 CET"
[28] "2018-01-25 00:00:00 CET"

我希望将TH视为矩阵,因为每一行都包含某些事件的开始时间和结束时间。我怎样才能确保TH以矩阵形式显示,而不是以我得到的形式显示?

在我的代码中,TS是一个14 x 2的unix时间戳矩阵,如下所示:

    > TS
              [,1]         [,2]
 [1,] 1.516748e+12 1.516750e+12
 [2,] 1.516750e+12 1.516779e+12
 [3,] 1.516779e+12 1.516780e+12
 [4,] 1.516780e+12 1.516781e+12
 [5,] 1.516781e+12 1.516790e+12
 [6,] 1.516790e+12 1.516793e+12
 [7,] 1.516793e+12 1.516794e+12
 [8,] 1.516794e+12 1.516794e+12
 [9,] 1.516794e+12 1.516801e+12
[10,] 1.516801e+12 1.516805e+12
[11,] 1.516805e+12 1.516809e+12
[12,] 1.516809e+12 1.516810e+12
[13,] 1.516810e+12 1.516825e+12
[14,] 1.516825e+12 1.516835e+12

接下来我申请了:

TH = as.POSIXct(TS / 1000,origin =" 1970-01-01",tz =" Europe / Paris")

获得TH,但它总是以上述形式输出。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

假设你的矢量看起来像这样:

temp <- c("2018-01-24 00:00:00 CET", "2018-01-24 00:24:34 CET", "2018-01-24 08:32:22 CET",
      "2018-01-24 08:42:12 CET", "2018-01-24 09:08:24 CET", "2018-01-24 11:41:36 CET",
      "2018-01-24 12:29:15 CET", "2018-01-24 12:31:47 CET", "2018-01-24 12:33:28 CET",
      "2018-01-24 14:32:03 CET", "2018-01-24 15:37:48 CET", "2018-01-24 16:53:36 CET",
      "2018-01-24 17:07:18 CET", "2018-01-24 21:10:23 CET", "2018-01-24 00:24:27 CET",
      "2018-01-24 08:32:15 CET", "2018-01-24 08:42:05 CET", "2018-01-24 09:08:13 CET",
      "2018-01-24 11:41:24 CET", "2018-01-24 12:29:08 CET", "2018-01-24 12:31:41 CET",
      "2018-01-24 12:33:11 CET", "2018-01-24 14:31:40 CET", "2018-01-24 15:37:25 CET",
      "2018-01-24 16:53:29 CET", "2018-01-24 17:07:11 CET", "2018-01-24 21:10:05 CET",
      "2018-01-25 00:00:00 CET")

temp <- (lubridate::ymd_hms(temp, tz = "CET"))

然后你可以将它转换为字符向量,然后再将其转换为矩阵:

mat <- matrix(as.character(temp), ncol = 2)
mat

现在如果你想做一些日期/时间操作,你需要把它变成一个数据框

df <- data.frame(mat)

然后你可以投射日期类型:

df$X1 <- lubridate::ymd_hms(df$X1, tz = "CET")
df$X2 <- lubridate::ymd_hms(df$X2, tz = "CET")