2017-01-10 39 views
1

部分看起来像:如何仅从strptime()中提取时间?数据

head(my_data[,c(1,2)], 3) 
     Date Time 
1 16/12/2006 17:24:00 
2 16/12/2006 17:25:00 
3 16/12/2006 17:26:00 

顺便说一句,str() $Date, $Time都是CHR现在。

我想,让他们两个的cols以正确的格式,所以我用

x <- as.Date(my_data$Date, "%d/%m/%Y") 

得到日期格式的第一个关口:

x[1:5] 
[1] "2006-12-16" "2006-12-16" "2006-12-16" "2006-12-16" "2006-12-16" 

但在第2个关口,当我试图使用

y <- strptime(my_data$Time, "%H:%M:%S") 

输出自动添加我的电脑的默认日期和时区。

y[1:4] 
[1] "2017-01-10 17:24:00 CST" "2017-01-10 17:25:00 CST" 
[2] "2017-01-10 17:26:00 CST" "2017-01-10 17:27:00 CST" 

如果我只想保持时间,没有日期和时区,该怎么办?
sub()用一些正则表达式来实现这个的唯一方法吗?

+2

如果你想有一个纯粹的时间对象另一种选择,你需要一个包,定义这样一类。你可以使用package'chron'。但是,我建议将日期和时间合并到一个'POSIXct'对象中。有些问题需要考虑,比如闰年和闰秒。 – Roland

回答

0

我们可以使用sub提取 '时间' 组件

sub(".*\\s+", "", y) 
#[1] "17:24:00" "17:25:00" "17:26:00" 

,如果我们想要一个time类,使用timeschron

library(chron) 
times(my_data$Time) 
#[1] 17:24:00 17:25:00 17:26:00 
+0

非常感谢!我想这就是我想要得到的。 'chron'包。 – hepeng

0

我们可以使用format来提取时间部分

format(strptime(y, "%H:%M:%S"),"%H:%M:%S") 

lubridate

library(lubridate) 
hms(my_data$Time) 
+0

使用'format'我可以只列出时间,用'str()'获得'chr'。但'format()'对于我的代码的其他部分非常有用。谢谢! – hepeng

+0

@hepeng从'lubridate'尝试'hms'功能。 –