首页 > 解决方案 > 对 NA 值使用 strptime

问题描述

我需要使用 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。我该如何解决这个问题?

标签: rstrptime

解决方案


你用的是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现在也可以使用。


推荐阅读