Search code examples
rdatetimechron

adding hours and minutes to 24 hour time in R


Im trying to find a way to create a column of the hours of arrival of different individuals from 18:30, by adding the hours and minutes to 18:30, but it doesnt work, and each time I try to convert the column format, of the hours and minutes I want to add, from "factor" to a time format (such as chron or POSIXct)it adds today`s date and I want to add only the hours and minutes without considering date.

For example, I want to add 03:38 hours to 18:30, which will be 22:08. So, I want to find a way to have a column with all the final hours (hours of arrival of each individual). another example is adding 00:47 hours to 18:30 which is 19:17.

I tried to do it by converting the hours+minutes to a numeric format and than add it to 18.5 (which is 18:30, just in a numeric format), and I reached final hours, but they are in a numeric format, and I wish them to be in an hour format. For example:

I added 3.6425980 (which is 03:38) to 18.5 (which is 18:30) and the final hour was 22.14260 (which is 22:08), but I don`t know how to convert 22.14260 to 22:08. I need to do it for a lot of data, so I need a code that does one of the above things.

Can someone help me?

thanks!


Solution

  • One option is to use lubridate

    time <- c("18:30", "18:30")
    duration <- c("3:38", "00:47")
    
    library(lubridate)
    hms(hm(time) + hm(duration), roll = T)
    #[1] "22H 8M 0S"  "19H 17M 0S"