Here is function to reformat the time string:
library(lubridate)
formatTimeString<- function(aTimeStr){
timeFlag <- tolower(str_sub(aTimeStr, start = -1))
timeNum <- tolower(str_sub(aTimeStr, end = -2))
stopifnot(timeFlag %in% c('m', 'a', 'n', 'p'))
daypartOffset <- c('m' = -12, # '12M' become 00:00
'n' = 0, # '12N' become 12:00
'a' = 0, 'p' = 12)
timeNum <- if_else(nchar(timeNum)<=2, paste0(timeNum,'00'), timeNum)
timeNum <- str_sub(paste0('0', timeNum), -4, -1)
ret <- lubridate::as_datetime(timeNum, format = '%H%M')
ret <- ret + hours(daypartOffset[timeFlag])
ret <- format(ret, '%H:%M')
return(ret)
}
testIn <- c('12M', paste0(1:11, 'A'),
'12N', paste0(1:11, 'P'))
testthat::expect_equal(formatTimeString(testIn),
str_sub(paste0('0', 0:23, ':00'), -4, -1))
No comments:
Post a Comment