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

11,461

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")
Share:
11,461

Related videos on Youtube

Klausos Klausos
Author by

Klausos Klausos

Updated on October 17, 2022

Comments

  • Klausos Klausos
    Klausos Klausos over 1 year

    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.

    • David Arenburg
      David Arenburg over 8 years
      Try converting to a correct format for starters, for example as.POSIXct(date1, format = "%FT%R") or for your specific example difftime(as.POSIXct('2015-10-05T20:57:00.000', format = "%FT%R"), as.POSIXct('2015-10-05T22:43:00.000', format = "%FT%R"), units = "mins")