3

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?

hepeng
  • 105
  • 1
  • 6
  • 2
    If you want to have a pure time object, you need a package that defines such a class. You could use package `chron`. However, I would suggest to combine date and time into a `POSIXct` object. There are nuisances such as leap years and leap seconds that need to be taken into account. – Roland Jan 10 '17 at 07:08

2 Answers2

4

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
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213