转换R中的Twitter时间戳

时间:2011-01-14 22:55:25

标签: datetime r

我是R的新手,处理日期很糟糕。以下日期从查询返回到Twitter搜索API,并作为字符串存储在我的数据框中。

  

“星期五,2011年1月14日03:01:22 +0000”

如何将此转换为日期并将时区更改为东部标准时间?

我认为这可能是直截了当的,但我涉足strptime而无处可去。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:11)

这对我有用(我在英国):

> ( str <- "Fri, 14 Jan 2011 03:01:22 +0000" )
[1] "Fri, 14 Jan 2011 03:01:22 +0000"

> ( str <- strptime(str, "%a, %d %b %Y %H:%M:%S %z", tz = "GMT") )
[1] "2011-01-14 03:01:22 GMT"

> ( dt.gmt <- as.POSIXct(str, tz = "GMT") )
[1] "2011-01-14 03:01:22 GMT"

> format(dt.gmt, tz = "EST", usetz = TRUE)
[1] "2011-01-13 22:01:22 EST"

日期/时间让我很困惑,所以我希望上述内容对你有用,即使你和GMT处于不同的时区,但我不能确定!

希望它至少有点帮助, 贝

答案 1 :(得分:6)

来自help(strptime)

> Sys.setlocale("LC_TIME", "C")
[1] "C"
> strptime("Tue, 23 Mar 2010 14:36:38 -0400",
+          "%a, %d %b %Y %H:%M:%S %z",
+          tz="GMT")
[1] "2010-03-23 18:36:38 GMT"

注意区域设置:如果不将其重置为C,该函数将尝试将工作日和月份缩写解析为本地化。

答案 2 :(得分:1)

我强烈建议您在CRAN上查看Jeff Gentry的twitteR软件包。在其他细节中,它为您解析日期字符串:

> library(twitteR)
> tweets = searchTwitter('#rstats')
> length(tweets)
[1] 25
> tweet = tweets[[1]]
> str(tweet)
Formal class 'status' [package "twitteR"] with 10 slots
  ..@ text        : chr "The Joy of Sweave \023 A Beginner\031s Guide to Reproducible Research with Sweave: Just& http://goo.gl/fb/APmCb #rstats"
  ..@ favorited   : logi FALSE
  ..@ replyToSN   : chr(0) 
  ..@ created     : POSIXct[1:1], format: "2011-01-18 04:48:05"
  ..@ truncated   : logi FALSE
  ..@ replyToSID  : num(0) 
  ..@ id          : num 2.72e+16
  ..@ replyToUID  : num(0) 
  ..@ statusSource: chr "&lt;a href=&quot;http://www.google.com/support/youtube/bin/answer.py?hl=en&amp;answer=164577&quot; rel=&quot;nofollow&quot;&gt;"| __truncated__
  ..@ screenName  : chr "Rbloggers"