2

I have a vector with DateTime character ("2014-04-17 23:33:00") and want to make a matrix with date and time as my columns.

This is my code:

  dat <- as.POSIXct(dates)
  date = data.frame(
   date=dat,
   time=format(dat, "%H:%M")
  )

I took a look at extract hours and seconds from POSIXct for plotting purposes in R and it helped, but the problem is that I only get 00:00 as the time in my time column. It does not extract the time from the dates vector.

Any help is appreciated.

Community
  • 1
  • 1
K.R.
  • 31
  • 2
  • 5
  • POSIX\*t are date-time objects, not just date or time. If you don't insert a date, it defaults to the current date; if you don't insert a time, it defaults to midnight. If you really can't just use POSIX\*t for everything (which it seems like you probably should, as you've got date-times), you could use alternate date/time objects. Options include the built-in `Date` format (of `as.Date`) and various options from the `lubridate` and `chron` packages. – alistaire Mar 29 '16 at 17:16

1 Answers1

3

Using the following vector as an example:

dates<- c("2012-02-06 15:47:00","2012-02-06 15:02:00")
dat <- as.POSIXct(dates)
date.df = data.frame(
  date=dat,
  time=format(dat, "%H:%M")
)

You will obtain the correct times ("%H:%M")

> date.df
             date  time
1 2012-02-06 15:47:00 15:47
2 2012-02-06 15:02:00 15:02
spsaaibi
  • 452
  • 4
  • 13