Lubridate vs date time functions in R

r
lubridate
datetime

#1

Hello,

Can somebody please help me to understand the differences between the lubridate package and other date time functions in R.
Which one is better or rather when should we use one above the other!!


#2

@shuvayan
I really like the lubridate package. it helps convert character variables into date time variables very nicely. the alternative is to use base R. Much much easier than strptime. Thats because the strptime function asks you to denote exact format type and you have to be exact in format type seperated by delimiters, % etc, while lubridate just breaks in down into mdy for month date year and hms for hour minute second.

    ## read in date/time info in format 'm/d/y h:m:s'
dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
times <- c("23:03:20", "22:29:56", "01:03:30", "18:21:03", "16:56:26")
x <- paste(dates, times)
x
strptime(x, "%m/%d/%y %H:%M:%S")
library(lubridate)
mdy(dates)
mdy_hms(x)

and the output

x
[1] “02/27/92 23:03:20” “02/27/92 22:29:56” “01/14/92 01:03:30” “02/28/92 18:21:03”
[5] "02/01/92 16:56:26"
strptime(x, “%m/%d/%y %H:%M:%S”)
[1] “1992-02-27 23:03:20 IST” “1992-02-27 22:29:56 IST” “1992-01-14 01:03:30 IST”
[4] “1992-02-28 18:21:03 IST” "1992-02-01 16:56:26 IST"
library(lubridate)
mdy(dates)
[1] “2092-02-27 UTC” “2092-02-27 UTC” “2092-01-14 UTC” “2092-02-28 UTC” "2092-02-01 UTC"
mdy_hms(x)
[1] “2092-02-27 23:03:20 UTC” “2092-02-27 22:29:56 UTC” “2092-01-14 01:03:30 UTC”
[4] “2092-02-28 18:21:03 UTC” “2092-02-01 16:56:26 UTC”

notice they have a different year base (1900 versus 2000) so please always check the conversion function before you apply

http://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html
and


#3

Thanks a lot @ajay_ohri sir. :smiley:
This is really very helpful!!