Home > Software engineering >  Correcting Time Format in R
Correcting Time Format in R

Time:11-24

I have a column of timestamp from a race; the time logs are given either in HH:MM:SS format or MM:SS format. I need to convert them from character to time format; I will be using as.POSIXct but first I am having issues dealing with the observations where the format is MM:SS as opposed to HH:MM:SS. When I apply as.POSIXct to the column, I get an error because all the observations don't have the same format. How do I add the "00:" leading up to a "59:34" timestamp?

Time "59:34" "32:07" "1:08:06"

CodePudding user response:

A base R option -

x <- c("59:34", "32:07", "1:08:06")
as.POSIXct(ifelse(nchar(x) > 5, x, paste0('00:', x)), format = '%T', tz = 'UTC')

#[1]"2021-11-24 00:59:34 UTC" "2021-11-24 00:32:07 UTC" "2021-11-24 01:08:06 UTC"

Since there is no date in the data as.POSIXct appends todays date.

CodePudding user response:

Here's a solution using lubridate::hms. If you want to use as.POSIXct, substitute your code for that.

It assumes that all values are either MM:SS or HH::MM::SS.

ts1 is the original values, ts2 pre-pended with "00:" where necessary and ts3 the final values.

library(dplyr)
library(stringr)
library(lubridate)

data.frame(ts1 = c("59:34", "32:07", "1:08:06")) %>% 
  mutate(ts2 = ifelse(str_count(ts1, ":") == 1, paste0("00:", ts1), ts1), 
         ts3 = hms(ts2))

Result:

      ts1      ts2      ts3
1   59:34 00:59:34  59M 34S
2   32:07 00:32:07   32M 7S
3 1:08:06  1:08:06 1H 8M 6S
  •  Tags:  
  • r
  • Related