简体   繁体   中英

How to convert hour:minute (HH:MM) string to 24 hour time format in R

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" 

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
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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM