hepeng
hepeng

Reputation: 105

How to extract ONLY time from strptime()?

Part of the data looks like:

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

By the way, str() $Date, $Time are all chr now.

I want to keep them in two cols with correct format, so I use

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

to get the 1st col in date format :

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

But in the 2nd col, when I'm trying to use

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

The output automatically add default date and timezone of my computer.

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"

What should I do if I just want to keep the time, without date and timezone?
Is sub() with some regular expression the only way to achieve this?

Upvotes: 3

Views: 8116

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

We can use format to extract the time component

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

Another alternative with lubridate package

library(lubridate)
hms(my_data$Time)

Upvotes: 2

akrun
akrun

Reputation: 886938

We can use sub to extract the 'time' component

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

and if we want a time class, use the times from chron

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

Upvotes: 4

Related Questions