Search code examples
rdatetimeposixct

How to convert Hour: minutes: seconds to decimal number in R


According to my lastest question here

I want to convert a column into the data.frame in date format to decimal number. However, I want to find another way but using the number of seconds from POSIXct. We can be multiplying this vector by c(1, 1/60, 1/3600) For example 02:20:00 will turn to 2.333333 Can I compute this into my data?

# A tibble: 10 x 3
   trip_id start_time          end_time           
     <int> <dttm>              <dttm>             
 1       1 2020-10-05 11:11:36 2020-10-05 12:12:54
 2       2 2020-10-05 16:09:16 2020-10-05 20:00:42
 3       3 2020-10-05 09:16:33 2020-10-05 11:16:27
 4       4 2020-10-05 14:16:38 2020-10-05 14:37:38
 5       5 2020-10-05 13:08:16 2020-10-05 13:13:16
 6       6 2020-10-05 11:02:23 2020-10-05 13:04:16
 7       7 2020-10-05 13:15:19 2020-10-05 15:54:19
 8   56562 2020-10-09 11:05:25 2020-10-09 13:37:44
 9   56563 2020-10-09 14:11:30 2020-10-09 14:12:30
10   56564 2020-10-09 16:00:40 2020-10-09 16:46:58
data <- structure(list(trip_id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 56562L,56563L, 56564L), start_time = structure(c(1601896296, 1601914156,1601889393, 1601907398, 1601903296, 1601895743, 1601903719, 1602241525,1602252690, 1602259240), tzone = "UTC", class = c("POSIXct","POSIXt")), end_time = structure(c(1601899974, 1601928042, 1601896587,1601908658, 1601903596, 1601903056, 1601913259, 1602250664, 1602252750,1602262018), tzone = "UTC", class = c("POSIXct", "POSIXt"))), row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame")) 

Thank you in advance.


Solution

  • Using R Base.

    df <- read.csv(text ="start_time    end_time
    05/10/2020 11:11:36 05/10/2020 12:12:54
    05/10/2020 16:09:16 05/10/2020 20:00:42
    05/10/2020 09:16:33 05/10/2020 11:16:27
    05/10/2020 14:16:38 05/10/2020 14:37:38
    05/10/2020 13:08:16 05/10/2020 13:13:16
    05/10/2020 11:02:23 05/10/2020 13:04:16
    05/10/2020 13:15:19 05/10/2020 15:54:19
    09/10/2020 11:05:25 09/10/2020 13:37:44
    09/10/2020 14:11:30 09/10/2020 14:12:30
    09/10/2020 16:00:40 09/10/2020 16:46:58
    ", sep="\t" )
    
    
    df$test <- lapply(str_split(str_sub(df$start_time,12), ":"),  
                      function(x) sum(as.numeric(unlist(x)) * c(1,1/60, 1/3600)))
    df
    
    
                start_time            end_time     test
    1  05/10/2020 11:11:36 05/10/2020 12:12:54 11.19333
    2  05/10/2020 16:09:16 05/10/2020 20:00:42 16.15444
    3  05/10/2020 09:16:33 05/10/2020 11:16:27 9.275833
    4  05/10/2020 14:16:38 05/10/2020 14:37:38 14.27722
    5  05/10/2020 13:08:16 05/10/2020 13:13:16 13.13778
    6  05/10/2020 11:02:23 05/10/2020 13:04:16 11.03972
    7  05/10/2020 13:15:19 05/10/2020 15:54:19 13.25528
    8  09/10/2020 11:05:25 09/10/2020 13:37:44 11.09028
    9  09/10/2020 14:11:30 09/10/2020 14:12:30 14.19167
    10 09/10/2020 16:00:40 09/10/2020 16:46:58 16.01111