在 NA 值上使用 strptime

Using strptime on NA values

我需要使用 strptime 函数来转换如下所示的时间戳:

Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014

根据需要,我已将其复制到 csv 文件中并将其读入 R:

timestamp_data <- read.table('timestamp_data.csv')

然后我尝试使用以下方法将其转换为可识别的时间:

timestamp_data_formatted <- strptime(timestamp_data[,1], format ="%a %b %d %H:%M:%S %z %Y")

当我尝试在 R 中查看格式化数据时,我仍然得到 NA 值。我认为问题是当我在 R 中查看我导入的 csv 数据时,它没有显示“+0000”,而是只显示 0。如何我可以解决这个问题吗?

您使用的是 read.table,而不是 read.csv。前者按空格拆分,因此将日期时间拆分为多列:

df <- read.table(text = 'Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014')

df
#>    V1  V2 V3       V4 V5   V6
#> 1 Tue Feb 11 12:18:36  0 2014
#> 2 Tue Feb 11 12:23:22  0 2014
#> 3 Tue Feb 11 12:26:26  0 2014
#> 4 Tue Feb 11 12:28:02  0 2014

str(df)
#> 'data.frame':    4 obs. of  6 variables:
#>  $ V1: Factor w/ 1 level "Tue": 1 1 1 1
#>  $ V2: Factor w/ 1 level "Feb": 1 1 1 1
#>  $ V3: int  11 11 11 11
#>  $ V4: Factor w/ 4 levels "12:18:36","12:23:22",..: 1 2 3 4
#>  $ V5: int  0 0 0 0
#>  $ V6: int  2014 2014 2014 2014

如果您使用 read.csv(带有合理的参数),它会起作用:

df <- read.csv(text = 'Tue Feb 11 12:18:36 +0000 2014
Tue Feb 11 12:23:22 +0000 2014
Tue Feb 11 12:26:26 +0000 2014
Tue Feb 11 12:28:02 +0000 2014', header = FALSE, stringsAsFactors = FALSE)

df$datetime <- as.POSIXct(df$V1, format = '%a %b %d %H:%M:%S %z %Y', tz = 'UTC')

df
#>                               V1            datetime
#> 1 Tue Feb 11 12:18:36 +0000 2014 2014-02-11 12:18:36
#> 2 Tue Feb 11 12:23:22 +0000 2014 2014-02-11 12:23:22
#> 3 Tue Feb 11 12:26:26 +0000 2014 2014-02-11 12:26:26
#> 4 Tue Feb 11 12:28:02 +0000 2014 2014-02-11 12:28:02

str(df)
#> 'data.frame':    4 obs. of  2 variables:
#>  $ V1      : chr  "Tue Feb 11 12:18:36 +0000 2014" "Tue Feb 11 12:23:22 +0000 2014" "Tue Feb 11 12:26:26 +0000 2014" "Tue Feb 11 12:28:02 +0000 2014"
#>  $ datetime: POSIXct, format: "2014-02-11 12:18:36" "2014-02-11 12:23:22" ...

我在这里使用 as.POSIXct 而不是 strptime,因为前者通常是您需要的,但 strptime 现在也可以使用。

我发现 lubridate 包使日期处理更容易,read_csv 来自 readr / tidyverse 不会自动设置因素。

library(lubridate)
library(tidyverse)

timestamp_data <- read_csv('timestamp_data.csv', col_names = FALSE)
timestamp_data$parsed_date <- parse_date_time(timestamp_data$X1, "%a %b %d %H:%M:%S %z %Y")