Pavel M
Pavel M

Reputation: 3

Converting numbers into time in R

My data looks like this:

 > str(m)
     int [1:8407] 930 1050 1225 1415 1620 1840 820 1020 1215 1410 ...

This is the time in hours and minutes. I'm trying to turn it into something (9:30, 12:10, 16:40, 8:25...).

> m1 <- strptime(m, "%H%M")
> head(m1)
[1] NA                         "2015-10-14 10:50:00 VLAT"
[3] "2015-10-14 12:25:00 VLAT" "2015-10-14 14:15:00 VLAT"
[5] "2015-10-14 16:20:00 VLAT" "2015-10-14 18:40:00 VLAT"
> str(m1)
 POSIXlt[1:8407], format: NA "2015-10-14 10:50:00" "2015-10-14 12:25:00" ...

How to convert a set of digits in time?

Upvotes: 0

Views: 1474

Answers (3)

akrun
akrun

Reputation: 887901

We format the numbers with sprintf to pad leading 0 for 3 digit numbers, use strptime and then use format to get the hour and min.

format(strptime(sprintf('%04d', v1), format='%H%M'), '%H:%M')
#[1] "09:30" "10:50" "12:25"

Or another option is

sub('(\\d{2})$', ':\\1', v1)
#[1] "9:30"  "10:50" "12:25"

data

v1 <- c(930, 1050,1225)

Upvotes: 0

Pierre L
Pierre L

Reputation: 28461

Using regex:

sub("(\\d{2})$", ":\\1", x)
 #[1] "9:30"  "10:50" "12:25" "14:15" "16:20" "18:40" "8:20" 
 #[8] "10:20" "12:15" "14:10"

A match is made on the last two digits and adds a colon before it.

Data

x <- c(930, 1050, 1225, 1415, 1620, 1840, 820, 1020, 1215, 1410)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389275

Another way is,

x <- c(645, 1234,2130)
substr(as.POSIXct(sprintf("%04.0f", x), format='%H%M'), 12, 16)

#[1] "06:45" "12:34" "21:30"

Upvotes: 0

Related Questions