Manipulate Dates with Lubridate

A quick tutorial on manipulation of dates with Lubridate package in R

library(lubridate)

Say you have a date-time vector

dtimes <- c("2002-06-09 12:45:40","2003-01-29 09:30:40", "2002-02-28 16:45:40","2006-11-13 20:00:40", "2012-07-17 17:30:40")

These are all characters actually

class(dtimes)

[1] "character"

Use the functionality in ymd_hms to convert these nicely to dates

dtimes <- ymd_hms(dtimes)

You can also use as_date if you don’t care about hour-mins-seconds format

as_date(dtimes)

[1] "2002-06-09" "2003-01-29" "2002-02-28" "2006-11-13" "2012-07-17"

These are all Dates now

class(dtimes)

[1] "POSIXct" "POSIXt" 

Use the %m+% to add months (without exceeding the last day of the new month)

dtimes %m+% months(11)

[1] "2003-05-09 12:45:40 UTC" "2003-12-29 09:30:40 UTC"
[3] "2003-01-28 16:45:40 UTC" "2007-10-13 20:00:40 UTC"
[5] "2013-06-17 17:30:40 UTC"

Conversely subtract with %m-%

dtimes %m-% months(11)

[1] "2001-07-09 12:45:40 UTC" "2002-02-28 09:30:40 UTC"
[3] "2001-03-28 16:45:40 UTC" "2005-12-13 20:00:40 UTC"
[5] "2011-08-17 17:30:40 UTC"

To manipulate days, use days

dtimes - days(25)

[1] "2002-05-15 12:45:40 UTC" "2003-01-04 09:30:40 UTC"
[3] "2002-02-03 16:45:40 UTC" "2006-10-19 20:00:40 UTC"
[5] "2012-06-22 17:30:40 UTC"

To manipulate hours, use hours

dtimes + hours(25)

[1] "2002-06-10 13:45:40 UTC" "2003-01-30 10:30:40 UTC"
[3] "2002-03-01 17:45:40 UTC" "2006-11-14 21:00:40 UTC"
[5] "2012-07-18 18:30:40 UTC"

These are some operations I found handy. Lubridate seriously lubris the dates 😀