0

Currently I have a column with time in the format yyyy-mm-dd hh:mm:ss, (eg. 2015-10-10 04:10:45) and I wish to extract the hour possibly using as.POSIXlt(x)$hour where x is my column.

Unfortunately, this function is returning a vector full of 0's, but if I do something like as.POSIXlt("2015-10-10 04:10:45")$hour I receive 4 which is what I want.

How can I do this with the whole column?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user3276768
  • 1,416
  • 3
  • 18
  • 28
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Apr 21 '16 at 10:37
  • 1
    Did you mean `as.POSIXlt( myData$x )$hour` ? – zx8754 Apr 21 '16 at 10:38

1 Answers1

3

I was just doing the exact same thing on my dataset...

format(as.POSIXct(df$datetime, format="%Y-%m-%d %H:%M:%S"), format="%H:%M:%S")
#[1] "04:10:45"
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • 1
    This did the job, thanks. – user3276768 Apr 21 '16 at 10:41
  • 4
    @user3276768 can you explain how is this answer better than your attempt and what isn't working? `as.POSIXlt(c("2015-10-10 04:10:45", "2015-10-10 05:10:45", "2015-10-10 06:10:45"))$hour` works perfectly fine for a vector. From what you wrote you wanted an integer hour not a character string with minutes and seconds. I have no idea what's going on here. – David Arenburg Apr 21 '16 at 10:44
  • @DavidArenburg I think he meant "`4` is NOT what I want" – Sotos Apr 21 '16 at 12:04