Duy Bui
Duy Bui

Reputation: 1396

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?

Upvotes: 18

Views: 21163

Answers (3)

Jerry T
Jerry T

Reputation: 1690

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.

Upvotes: 3

akrun
akrun

Reputation: 886938

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)

Upvotes: 13

Michele Usuelli
Michele Usuelli

Reputation: 2000

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"

Upvotes: 20

Related Questions