I have a date/time column in an inconsistent format:
df <- data.frame(date.time=c("10-29-2022 09:46:40", "02-27-2023 22:53:53", "12-15-2022 02:54:03", "01-09-2023 14:44", "03-05-2023 14:58", "02-18-2023 19:46:35", "12-10-2022 16:50"))
I want to add ":00" to the time stamps that don’t include seconds (notice some strings are shorter than others). I can find the strings without seconds using gsubs(pattern=) but when I try to add on ":00" to the end I’m replacing the whole string:
df %>%
mutate_at(.vars = "date.time",
.funs = gsub,
pattern = "^\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d$",
replacement = "\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d:00")
>Solution :
In this case, you can use a simple ifelse with nchar and paste0 with no need for regex:
df$date.time_new <- ifelse(nchar(df$date.time) < max(nchar(df$date.time)),
paste0(df$date.time, ":00"),
df$date.time)
Output:
date.time date.time_new
1 10-29-2022 09:46:40 10-29-2022 09:46:40
2 02-27-2023 22:53:53 02-27-2023 22:53:53
3 12-15-2022 02:54:03 12-15-2022 02:54:03
4 01-09-2023 14:44 01-09-2023 14:44:00
5 03-05-2023 14:58 03-05-2023 14:58:00
6 02-18-2023 19:46:35 02-18-2023 19:46:35
7 12-10-2022 16:50 12-10-2022 16:50:00