Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

obtain hour from DateTime vector

Tags:

date

time

r

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?

like image 653
user1407388 Avatar asked May 21 '12 10:05

user1407388


People also ask

How to extract hours from datetime in MATLAB?

h = hour( t ) returns the hour component for each date and time specified in t . The h output is a double array and contains integer values from 0 to 23. To assign values to the hour component of values in t , use t.

What is Datevec in Matlab?

DateVector = datevec( t ) converts the datetime or duration value t to a date vector—that is, a numeric vector whose six elements represent the year, month, day, hour, minute, and second components of t .

How do I get the current date and time in Matlab?

t = now returns the current date and time as a serial date number.


2 Answers

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
like image 90
Andrie Avatar answered Nov 07 '22 19:11

Andrie


Or generically, not treating them as dates, you can use the following provided that the time and dates are padded correctly.

library(stringr)
df <- data.frame(DateTime = c("2010-01-01 00:00", "2010-01-01 01:00", "2010-01-01 02:00", "2010-01-01 03:00"))
df <- data.frame(df, Time = str_sub(df$DateTime, -5, -1))

It depends on your needs really.

like image 32
R J Avatar answered Nov 07 '22 21:11

R J