How to convert time to decimal

后端 未结 3 1965
难免孤独
难免孤独 2020-12-03 20:11

I have a large data set containing time in hh:mm:ss format and I would like to convert these to a decimal format while ignoring the hours (hh). I have used strptime but this

相关标签:
3条回答
  • 2020-12-03 20:47

    There is probably a lubridate function for this, but I'd do it like this:

    x <-  "01:18:30"
    
    y <- (as.numeric(as.POSIXct(paste("2014-01-01", x))) - 
       as.numeric(as.POSIXct("2014-01-01 0:0:0")))/60
    #[1] 78.5
    

    Ignoring the hours:

    y%%60
    #[1] 18.5
    
    0 讨论(0)
  • 2020-12-03 20:58

    It's relatively trivial to write a function which does the conversion for you. Assuming your input is character vectors:

    > decimateTime=function(time) {
    +     time=as.numeric(unlist(strsplit(time, ":")))
    +     time = time[1]*60+time[2]+time[3]/60
    +     return(time)
    + }
    > times=c('00:01:38', '01:18:30', '13:18:01')
    > print(sapply(times,decimateTime))
    00:01:38   01:18:30   13:18:01 
    1.633333  78.500000 798.016667 
    
    0 讨论(0)
  • 2020-12-03 21:05

    You can use stringsplit and sapply

    dat<-c('00:01:38','01:18:30')
    sapply(strsplit(dat,":"),
           function(x) {
             x <- as.numeric(x)
             x[1]*60+x[2]+x[3]/60
           }
    )
    

    Result:

    [1]  1.633333 78.500000
    

    Credits go to @Joris Meys

    Just extended his example: How to convert time (mm:ss) to decimal form in R

    0 讨论(0)
提交回复
热议问题