24

I have a vector of time that is in the format of factor. For instance, Time[1] is 8:01:01, class(Time[1]) is factor.

Now I want to extract hours and minute from this vector. What is the most computational efficient way of doing it? My vector is very large. Thank you so much,

Jaap
  • 81,064
  • 34
  • 182
  • 193
NewbieDave
  • 1,199
  • 3
  • 12
  • 23
  • 1
    Dirk's approach worked for me - Check it out http://stackoverflow.com/questions/23348992/convert-factor-to-date-time-in-r or http://stackoverflow.com/questions/16239646/how-format-factor-hour-and-minute-as-time-in-r – nick Nov 24 '15 at 21:29

6 Answers6

25

Try this:

format(strptime(Time,"%H:%M:%S"),'%H:%M')
[1] "08:01"
Shenglin Chen
  • 4,504
  • 11
  • 11
16

One way with the lubridate package would be:

Time <- factor("08:01:01")
lubridate::hms(as.character(Time))

Edit

To extract hours and minutes:

library(lubridate)
Time <- factor("08:01:01")

# parese date
a <- hms(as.character(Time))

# get hours
hour(a)

# get minutes
minute(a)
johannes
  • 14,043
  • 5
  • 40
  • 51
10

You could also try a combination of converting your factor to a POSIXt object and then using the format function. I'm not sure how efficient this method is though.

Time <- factor("08:01:01")
hour = format(as.POSIXct(Time,format="%H:%M:%S"),"%H")
minute = format(as.POSIXct(Time,format="%H:%M:%S"),"%M")

paste(hour,minute,sep=":")
[1] "08:01"
s_scolary
  • 1,361
  • 10
  • 21
  • Thank you so much. That's the current method I'm using. I was hoping to make it faster though. – NewbieDave Nov 24 '15 at 21:34
  • maybe try the chron package. `require(chron)` `times(Time,out.format="h:m")`. The only problem with this method is that the hour and minutes aren't separated by a colon. output: `[1] 0801`. But maybe this will speed things up for you. – s_scolary Nov 24 '15 at 21:44
5

What about this

 Time  <- factor("08:01:01")
 Time2 <- strptime(Time, "%H:%M:%S")
 Time3 <- format(Time2, "%H:%M")

Time3

[1] "08:01"

Boro Dega
  • 393
  • 1
  • 3
  • 13
4

Simpler solution: format(Sys.time(), "%H:%M")

ZF007
  • 3,708
  • 8
  • 29
  • 48
3

The data.table package handles date times. You could use its convenience functions hour() and minute() to extract specific times and paste0() them together.

require(data.table)
time = Sys.time()
paste0(hour(time), ':', minute(time))
andschar
  • 3,504
  • 2
  • 27
  • 35