在R中转换时间

时间:2016-04-07 14:34:35

标签: r graph statistics

您好我似乎无法将我在CSV文件中的时间转换为R中的可读格式。

CSV文件中的时间格式如下:

"Mon Oct 19 17:26:18 EDT 2015"

我需要将它转换为R中可读的内容。

我使用以下脚本进行转换,但似乎无效。

Time <- strptime(csv.data$Time,format="%m/%d/%Y  %R")  # %R is equiv to %H:%M
Time <- strptime(csv.data$Time,format="%m/%d/%Y  %H:$M")

有人可以就如何解决这个问题给我任何建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

一旦你摆脱原始数据中的时区部分,这个就可以了:

s <- 'Mon Oct 19 17:26:18 2015'
t <- strptime(s, '%a %b %d %H:%M:%S %Y')

输出如下:

t
[1] "2015-10-19 17:26:18 EDT"

你可以这样做:

s <- 'Mon Oct 19 17:26:18 EDT 2015'
gsub('EDT', '', s)

上面的示例代码与数据框:

df <- data.frame(s = rep(format(Sys.time(), '%a %b %d %H:%M:%S %Z %Y'), 10))
df
                              s
1  Thu Apr 07 11:33:50 EDT 2016
2  Thu Apr 07 11:33:50 EDT 2016
3  Thu Apr 07 11:33:50 EDT 2016
4  Thu Apr 07 11:33:50 EDT 2016
5  Thu Apr 07 11:33:50 EDT 2016
6  Thu Apr 07 11:33:50 EDT 2016
7  Thu Apr 07 11:33:50 EDT 2016
8  Thu Apr 07 11:33:50 EDT 2016
9  Thu Apr 07 11:33:50 EDT 2016
10 Thu Apr 07 11:33:50 EDT 2016

df$s <- gsub('EDT', '', df$s)
df
                           s
1  Thu Apr 07 11:33:50  2016
2  Thu Apr 07 11:33:50  2016
3  Thu Apr 07 11:33:50  2016
4  Thu Apr 07 11:33:50  2016
5  Thu Apr 07 11:33:50  2016
6  Thu Apr 07 11:33:50  2016
7  Thu Apr 07 11:33:50  2016
8  Thu Apr 07 11:33:50  2016
9  Thu Apr 07 11:33:50  2016
10 Thu Apr 07 11:33:50  2016

df$t <- strptime(df$s, '%a %b %d %H:%M:%S %Y')
df
                           s                   t
1  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
2  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
3  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
4  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
5  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
6  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
7  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
8  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
9  Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50
10 Thu Apr 07 11:33:50  2016 2016-04-07 11:33:50

str(df)
'data.frame':   10 obs. of  2 variables:
 $ s: chr  "Thu Apr 07 11:33:50  2016" "Thu Apr 07 11:33:50  2016" "Thu Apr 07 11:33:50  2016" "Thu Apr 07 11:33:50  2016" ...
 $ t: POSIXlt, format: "2016-04-07 11:33:50" "2016-04-07 11:33:50" "2016-04-07 11:33:50" ...