R 中的日期时间操作

Date Time Manipulation in R

我的数据集有一个名为 created_at 的列,如下所示:

**created_at** 

Tue Feb 21 14:14:34 UTC 2017  
Wed Feb 22 00:00:12 UTC 2017

...

我想将其格式化为 DateTime 并提取个人信息,即提取工作日、月、日、时间和年的单独列。

我尝试类似的方法:

date_b <- str_split(amt$created_at, " ")

week <- as.data.frame(sapply(date_b, "[", 1))
month <- as.data.frame(sapply(date_b, "[", 2))
day <- as.data.frame(sapply(date_b, "[", 3))
year <- as.data.frame(sapply(date_b, "[", 6))
hour <- as.data.frame(sapply(date_b, "[",4))  

aux1 <- strptime(hora[,1], format="%H:%M:%S")

没有运气。

有什么帮助吗?

里卡多

strptime 要求格式精确匹配

> test <- "Wed Feb 22 00:00:12 UTC 2017"
> strptime(test, "%a %b %d %T UTC %Y", tz = "GMT")
[1] "2017-02-22 00:00:12 GMT"

为了提取特定值,我倾向于在 tidyr 中使用 separate(),例如

> col1 = c("a", "b")
> col2 = c("Tue Feb 21 14:14:34 UTC 2017", "Wed Feb 22 00:00:12 UTC 2017")
> col3 = c("test", "test2")

> df <- data.frame(col1, col2, col3)

> df

  col1                         col2  col3
1    a Tue Feb 21 14:14:34 UTC 2017  test
2    b Wed Feb 22 00:00:12 UTC 2017 test2

> df %>% 
    separate(col2, 
             into = c("Weekday", "Month", "Date", "Time", "Timezone", "Year"),
             sep = " ",
             remove = FALSE)

  col1                         col2 Weekday Month Date     Time Timezone Year  col3
1    a Tue Feb 21 14:14:34 UTC 2017     Tue   Feb   21 14:14:34      UTC 2017  test
2    b Wed Feb 22 00:00:12 UTC 2017     Wed   Feb   22 00:00:12      UTC 2017 test2

希望对您有所帮助!