atomi kise
atomi kise

Reputation: 93

Extract hour on dataframe

I am a novice in R and I am looking for a way to extract only hour minute and seconde in my dataframe. I have tried some libraries but without sucess.

Here is my code for the moment:

daily_data = read.csv("/Us/eco.csv", header=TRUE, stringsAsFactors=FALSE)

daily_hour= daily_data$time

daily_hour

Here is how My date look like :

 [1] "2016-08-19 17:45:19" "2016-08-19 17:45:19" "2016-08-19 17:45:19" "2016-08-19 17:45:19"
   [5] "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19"
   [9] "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19" "2016-08-19 18:59:19"
  [13] "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 19:27:07"
  [17] "2016-08-19 19:27:07" "2016-08-19 19:27:07" "2016-08-19 23:33:46" "2016-08-19 23:33:46"
  [21] "2016-08-19 23:33:46" "2016-08-19 23:33:46" "2016-08-20 07:13:32" "2016-08-20 07:13:32"
  [25] "2016-08-20 07:13:32" "2016-08-20 07:13:32" "2016-08-20 08:52:12" "2016-08-20 08:52:12"
  [29] "2016-08-20 08:52:12" "2016-08-20 08:52:12" "2016-08-20 10:06:53" "2016-08-20 10:06:53"
  [33] "2016-08-20 10:06:53" "2016-08-20 10:06:53" "2016-08-20 10:06:56" "2016-08-20 10:06:56"

Upvotes: 0

Views: 73

Answers (3)

Santosh M.
Santosh M.

Reputation: 2454

If your date format is consistent, you can also use substr.

substr(daily_hour, 12, 19)

substr("2016-08-19 17:45:19", 12, 19)
[1] "17:45:19"

Upvotes: 0

Brendan A.
Brendan A.

Reputation: 1268

hms <- sub('\\d+-\\d+-\\d+ ', '', daily_hour) will extract the hour:minute:seconds part of your strings as strings. If you need to then separate those into additional variables, you have two options.

# Option 1
hours <- sub(':\\d+:\\d+', '', hms)
mins <- sub('\\d+:(\\d+):\\d+', '\\1', hms)
secs <- sub('\\d+:\\d+:', '', hms)

# Option 2
daily_hour <- as.POSIXct(daily_hour)
hours <- as.numeric(format(daily_hour, "%H"))
mins <- as.numeric(format(daily_hour, "%M"))
secs <- as.numeric(format(daily_hour, "%S"))

Upvotes: 1

Aleksandr
Aleksandr

Reputation: 1914

Suppose your data:

daily_hour = data.frame(time = c("2016-08-19 17:45:19", "2016-08-19 17:45:36"))

Then split it by sep = " " and take second element of a list, you will get a vector of hh:mm:ss:

sapply(daily_hour$time, function(x) strsplit(as.character(x), " ")[[1]][2])

Upvotes: 0

Related Questions