Nodedeveloper101
Nodedeveloper101

Reputation: 441

How to get hours and minutes by subtracting two dates with R

I have two columns in R and both of them are dates with the following format..

   1/2/2015 3:00:00 PM

I need to create a new column which is 'Hours' which would be the amount of hours have passed between the two dates. I've tried this but it gives me the difference in days..

col1 <- df$collection.when
col2 <- df$discardable_when
col3 <- as.Date(col1) - as.Date(col2)
head(col3)
# > Time differences in days
[1] -393   NA   NA   NA -485   NA

EDIT:

It seems that @HubertL answer would be the correct solution, however I cannot get complete a data.frame for an unknown reason.. heres a screenshot that shows my workflow. Any help is greatly appreciated.

rstudio

Upvotes: 1

Views: 2483

Answers (2)

HubertL
HubertL

Reputation: 19544

Maybe Dates don't have time.

You probably could use POSIXct :

a <- as.POSIXct(strptime("1/2/2015 2:00:00 PM", "%m/%d/%Y %I:%M:%S %p"), tz="")
b <- as.POSIXct(strptime("1/2/2015 5:00:00 PM", "%m/%d/%Y %I:%M:%S %p"), tz="")
c <- b - a; 
units(c) <- "hours"
as.numeric(c)
[1] 3

Upvotes: 0

Se&#241;or O
Se&#241;or O

Reputation: 17422

Instead of as.Date, use as.POSIXct which includes time information.

You can also use difftime to specify units of output.

time1 = as.POSIXct("2015-01-01 01:00:00")
time2 = as.POSIXct("2015-03-02 05:00:00 PM")

difftime(time2, time1, units = "min")
Time difference of 86640 mins

Upvotes: 1

Related Questions