user6678274 user6678274 - 3 months ago 22
R Question

How to convert times over 24:00:00 in R

In R I have this data.frame

24:43:30 23:16:02 14:05:44 11:44:30 ...


Note that some of the times are over 24:00:00 ! In fact all my times are within
02:00:00
to
25:59:59
.

I want to subtract all entries in my dataset
data
with 2 hours. This way I get a regular data-set. How can I do this?

I tried this

strptime(data, format="%H:%M:%S") - 2*60*60


and this work for all entries below
23:59:59
. For all entries above I simply get
NA
since the
strptime
command produce
NA
to all entries above
23:59:59
.

Answer

Using lubridate package can make the job easier!

> library(lubridate)
> t <- '24:43:30'
> hms(t) - hms('2:0:0')
[1] "22H 43M 30S"

Update:

Converting the date back to text!

> substr(strptime(hms(t) - hms('2:0:0'),format='%HH %MM %SS'),12,20)
[1] "22:43:30"

Adding @RHertel's update:

format(strptime(hms(t) - hms('2:0:0'),format='%HH %MM %SS'),format='%H:%M:%S')

Better way of formating the lubridate object:

s <- hms('02:23:58) - hms('2:0:0')
paste(hour(s),minute(s),second(s),sep=":")
"0:23:58"