【问题标题】:converting time in factor format into timestamp将因子格式的时间转换为时间戳
【发布时间】:2014-05-30 06:39:21
【问题描述】:

我已经下载了 json 格式的推文,将其转换为 csv,然后将其读入 R。现有时间戳为因子格式,如下所示。我应该如何将其转换为可以绘制的时间戳?

[1] Fri May 09 07:55:12 +0000 2014 Fri May 09 07:55:12 +0000 2014 Fri May 09 07:55:12 +0000 2014
[4] Fri May 09 07:55:12 +0000 2014 Fri May 09 07:55:12 +0000 2014 Fri May 09 07:55:12 +0000 2014
516 Levels: Fri May 09 07:55:12 +0000 2014 ... Fri May 09 09:15:07 +0000 2014

【问题讨论】:

  • strptime(as.character(test$time_created), '%a %B %d %H:%M:%S +0000 %Y') 这样的东西会起作用吗?
  • @tonytonov,您可能应该将其发布为未来读者的答案
  • @tonytonov,谢谢,但它会导致创建的多个列都充满了 NA。尽管如此,我已经通过以下 Sven 的解决方案解决了这个问题。
  • @eugeneyan 可能是因为May被缩写后仍然是May,所以用%b而不是%B试试。

标签: r time


【解决方案1】:

我想你的问题已经回答了 => Convert Twitter Timestamp in R

但如果你想更简单,你可以使用 twitteR 库。

> tweets <- userTimeline("BarackObama",n=100)
> df <- do.call("rbind",lapply(tweets, as.data.frame))
> names(df)
 [1] "text"          "favorited"     "favoriteCount" "replyToSN"     "created"       "truncated"    
 [7] "replyToSID"    "id"            "replyToUID"    "statusSource"  "screenName"    "retweetCount" 
[13] "isRetweet"     "retweeted"     "longitude"     "latitude"  

我们可以直接绘制创建状态日期

【讨论】:

    【解决方案2】:

    您可以在应用as.POSIXct 之前删除字符串中不必要的部分。这可以通过gsub 来完成:

    x <-  as.factor(c("Fri May 09 07:55:12 +0000 2014", 
                      "Fri May 09 07:55:12 +0000 2014"))
    
    as.POSIXct(gsub("^.+? | \\+\\d{4}","", x),
              format = "%b %d %X %Y")
    # [1] "2014-05-09 07:55:12 CEST" "2014-05-09 07:55:12 CEST"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 2016-11-26
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多