Convert time from numeric to time format in R

17,129

Solution 1

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"

Solution 2

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)

Solution 3

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.

Share:
17,129
Duy Bui
Author by

Duy Bui

Updated on June 11, 2022

Comments

  • Duy Bui
    Duy Bui almost 2 years

    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?

  • Duy Bui
    Duy Bui over 9 years
    This is not exactly what I'm looking for my friend, though it solves the conversion problem somehow. The result is now containing the date of 1970-01-01, while I actually only want the time value
  • Michele Usuelli
    Michele Usuelli over 9 years
    You can use substring to extract the time. nTime <- 0.5; datePosix <- as.POSIXct((nTime) * 60 * 60 * 24, origin = "1970-01-01", tz = "UTC"); substring(datePosix, 12, 19)