obtain hour from DateTime vector

date, r, time

Solution

Use `format` or `strptime` to extract the time information.

Create a POSIXct vector:

x <- seq(as.POSIXct("2012-05-21"), by=("+1 hour"), length.out=5)

Extract the time:

data.frame(
  date=x,
  time=format(x, "%H:%M")
)

                 date  time
1 2012-05-21 00:00:00 00:00
2 2012-05-21 01:00:00 01:00
3 2012-05-21 02:00:00 02:00
4 2012-05-21 03:00:00 03:00
5 2012-05-21 04:00:00 04:00

If the input vector is a character vector, then you have to convert to POSIXct first:

Create some data

dat <- data.frame(
  DateTime=format(seq(as.POSIXct("2012-05-21"), by=("+1 hour"), length.out=5), format="%Y-%m-%d %H:%M")
)
dat
          DateTime
1 2012-05-21 00:00
2 2012-05-21 01:00
3 2012-05-21 02:00
4 2012-05-21 03:00
5 2012-05-21 04:00

Split time out:

data.frame(
  DateTime=dat$DateTime,
  time=format(as.POSIXct(dat$DateTime, format="%Y-%m-%d %H:%M"), format="%H:%M")
)

          DateTime  time
1 2012-05-21 00:00 00:00
2 2012-05-21 01:00 01:00
3 2012-05-21 02:00 02:00
4 2012-05-21 03:00 03:00
5 2012-05-21 04:00 04:00

Problem

I have a DateTime vector within a data.frame where the data frame is made up of 8760 observations representing hourly intervals throughout the year e.g. ``` 2010-01-01 00:00 2010-01-01 01:00 2010-01-01 02:00 2010-01-01 03:00 ``` and so on. I would like to create a data.frame which has the original DateTime vector as the first column and then the hourly values in the second column e.g. ``` 2010-01-01 00:00 00:00 2010-01-01 01:00 01:00 ``` How can this be achieved?

Original source