Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get difference (in minutes) between two date strings?

Tags:

date

r

difftime

I have two dates:

date1 <- '2015-10-05T20:57:00.000'
date2 <- '2015-10-05T22:43:00.000'

1) I need to know the difference in minutes 2) Also I want to extract year, month, day and hour.

This is how I tried to solve these tasks:

1) time <- difftime(date1,date2,units="mins") # the result is 0 instead of 106.

2) I want to us "lubridate", but not sure how to apply it to my format.

like image 687
Klausos Klausos Avatar asked Oct 11 '15 18:10

Klausos Klausos


1 Answers

You can transform the dates to POSIXlt class and use the functions of lubridate package:

date1 = as.POSIXlt('2015-10-05T20:57:00.000',format="%Y-%m-%dT%H:%M:%S")
date2 = as.POSIXlt('2015-10-05T22:43:00.000',format="%Y-%m-%dT%H:%M:%S")
install.packages("lubridate")
library(lubridate)
year(date1)
month(date1)
day(date1)
hour(date1)

once you have transformed both dates to POSIXlt class (be careful with the format argument) you can get the difference in minutes too:

difftime(date1,date2,units="mins")
like image 175
nestor556 Avatar answered Nov 15 '22 05:11

nestor556