The original question asks how to replace colons in time values with periods so differences can be calculated. Unfortunately, since there are only 60 minutes in an hour, 14:30 (2:30 PM) does not equal 14.30. Therefore, any math operations on the decimal versions of time values is likely to introduce errors.
For example, if someone slept between 6:00 PM and 11:30PM, the time slept is 5.5 hours, not 11.3 - 6.0 = 5.3.
Complicating matters is the fact that if the end times for sleep occur on the following day (i.e. someone goes to sleep at 10PM and wakes up at 6:00AM the next day, the dates are required for the math to be correct.
Fortunately we can do calculate differences of date time values relatively simply with the lubridate
package.
Without a minimal reproducible example, we'll create some data that has person names and start / end dates & times for sleeping.
# create a data frame with time data
aFile <- "name,startTime,endTime
Jane,2023-03-01 20:00,2023-03-02 06:00
Joe,2023-03-01 18:00,2023-03-02 04:30
Kuthilda,2023-03-01 19:37,2023-03-02 02:10
Patricia,2023-03-02 06:00,2023-03-02 14:00"
df <- read.csv(text=aFile)
As specified in this example the date time information is read as character strings, so next we'll load the lubridate
package and use its parse_date_time()
function to calculate the sleep times.
library(lubridate)
df$sleepTime <- parse_date_time(df$endTime,"%Y-%m-%d %H:%M") - parse_date_time(df$startTime,"%Y-%m-%d %H:%M")
Finally, we print the results.
df
> df
name startTime endTime sleepTime
1 Jane 2023-03-01 20:00 2023-03-02 06:00 10.00 hours
2 Joe 2023-03-01 18:00 2023-03-02 04:30 10.50 hours
3 Kuthilda 2023-03-01 19:37 2023-03-02 02:10 6.55 hours
4 Patricia 2023-03-02 06:00 2023-03-02 14:00 8.00 hours