Reputation: 345
One of the columns in my data frame labelled Time has times in HH:MM minutes but these are in character format like so:
Time
----------
02:14
04:16
01:15
12:30
13:50
I wish to convert the times to 24 hour time format, like so:
| Time | Time_Converted
---------------
| 02:14 | 14:14
| 04:16 | 16:16
| 01:15 | 13:15
| 12:30 | 12:30
| 13:50 | 13:50
I tried the following:
h1$Time_Converted <- strftime(h1$Time, format="%H:%M")
But this returns date (not required) and time and it is not in the 24 hour fomat:
[1] "2021-06-01 02:14:00 AEST"
Upvotes: 0
Views: 794
Reputation: 370
library(tidyverse)
library(lubridate)
data.frame(time = c('02:14', '04:16', '01:15', '12:30', '13:50')) %>%
mutate(
time = hm(time),
time_converted = if_else(time < hours(12), time + hours(12), time))
Upvotes: 1
Reputation: 79338
You could do:
transform(df, new=paste(as.numeric(substr(Time, 1, 2))%%12+12, substr(Time, 4, 5), sep=":"))
Time new
1 02:14 14:14
2 04:16 16:16
3 01:15 13:15
4 12:30 12:30
5 13:50 13:50
Using tidyverse:
library(tidyverse)
df %>%
separate(Time, c('hr', 'min'), remove = FALSE) %>%
mutate(hr = sprintf('%02d', as.numeric(hr) %% 12 + 12)) %>%
unite(Time_converted, hr, min, sep = ':')
Time Time_converted
1 02:14 14:14
2 04:16 16:16
3 01:15 13:15
4 12:30 12:30
5 13:50 13:50
Upvotes: 1