Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time from numeric to time format in R

I read data from an xls file. Apparently, the time is not in the right format. It is as follows (for example)

0.3840277777777778
0.3847222222222222
0.3854166666666667

Indeed, they should be

09:12
09:13
09:13

I don't know how to convert it to the right format. I searched several threads and all of them are about converting the date (with/without time) to the right format.

Can somebody give me any clues?

like image 237
Duy Bui Avatar asked Jan 20 '15 10:01

Duy Bui


3 Answers

You can use as.POSIXct after having multiplied your number by the number of seconds in a day (60 * 60 * 24)

nTime <- c(0.3840277777777778, 0.3847222222222222, 0.3854166666666667)
format(as.POSIXct((nTime) * 86400, origin = "1970-01-01", tz = "UTC"), "%H:%M")
## [1] "09:13" "09:14" "09:15"
like image 125
Michele Usuelli Avatar answered Sep 20 '22 19:09

Michele Usuelli


Another option is times from chron

library(chron)
times(nTime)
#[1] 09:13:00 09:14:00 09:15:00

To strip off the seconds,

substr(times(nTime),1,5)
#[1] "09:13" "09:14" "09:15"

data

nTime <- c(0.3840277777777778, 0.3847222222222222, 0.3854166666666667)
like image 45
akrun Avatar answered Sep 21 '22 19:09

akrun


For people who want the opposite way: given the 09:13:00, get 0.3840278

as.numeric(chron::times("09:13:00"))

Essentially, the idea is that one whole day is 1,so noon (12pm) is 0.5.

like image 45
Jerry T Avatar answered Sep 20 '22 19:09

Jerry T