Home > Software engineering >  Convert hours in decimal to duration and add to another column
Convert hours in decimal to duration and add to another column

Time:05-17

I have one column that is a time of day (start_time), and a second that is a duration in hours that's in decimal format (duration_hours).

I'd like to convert the duration into HH:MM and then add it to the start time to create a new variable (end_time) that's time of day when the experiment stopped.

  1. How do I convert the decimal to HH:MM? I tried as_duration but it made it into seconds

  2. How do I then add that duration to the start time to make another time of day?

Thank you!

library(tidyr)
library(hms)

data <- tribble(
  ~id, ~start_time, ~duration_hours,
  #--/---/---
  "a","6:30:00",6.47,
  "b", "17:05:30",5.30
)

data$start_time<-hms::as_hms(data$start_time)

Created on 2022-05-16 by the reprex package (v2.0.1)

CodePudding user response:

We can use

library(lubridate)
hms::hms(seconds_to_period(data$duration_hours * 3600))

CodePudding user response:

The hms is just the number of seconds, so you may do

transform(data, end_time=as_hms(as.POSIXct(paste(Sys.Date(), start_time))   duration_hours*60^2))
#   id start_time duration_hours end_time
# 1  a   06:30:00           6.47 12:58:12
# 2  b   17:05:30           5.30 22:23:30

Or using strftime

transform(data, end_time=strftime(as.POSIXct(paste(Sys.Date(), start_time))   duration_hours*60^2, "%T"))
#   id start_time duration_hours end_time
# 1  a    6:30:00           6.47 12:58:12
# 2  b   17:05:30           5.30 22:23:30
  • Related