# practice with lubridate # convert formatted strings to dates library(lubridate) date_ymd <- ymd_hms("2017-12-28 10:26:20") date_mdy <- mdy_hm("12/28/17 11:44") date_hm1 <- dmy_hm("28.12.17 9:30AM") date_hm2 <- dmy_hm("28.12.17 9:30PM") # there are functional available for just specifying a date also, numbers can be used as input to these functions mdy("March 6, 2015") dmy("06/03/2015") dmy(06032015) ydm("1988/21/2") # produces objects of class DATE d_made <- make_date(year = 2018, month = 9, day = 24) # produces objects of class DATETIME dt <- make_datetime(year = 2018, month = 9, day = 24, hour = 13L, min = 15L) # Extract pieces from the date year(dt) #extract year month(dt) # extract month mday(dt) # extract month yday(dt) #extract day count for the year wday(dt) #returns the day of the week as a decimal wday(dt, label=TRUE) #set label to TRUE to get string abbr. hour(dt) # extract the hour from the dt minute(dt) #extract the minute from dt second(dt) #extract the second from dt dt1 <- dt # these functions can also be use for setting values year(dt1) <- 2017 month(dt1) <- 7 day(dt1) <- 4 # convert to a date class with the date function dd <- date(dt1) # check for a leap year leap_year(c(dt1,dt)) # get current datetime using different packages lubridate::today() # get pieces of today's date week <- wday(today(),label=TRUE,abbr = FALSE) base::date() Sys.Date() Sys.timezone() now() # determin if a datetime is in am am(now()) # full datetime - should return TRUE if run before noon, FALSE if run after 12:00pm am(today()) # today is only a date - time defaults to beginning of the day # create a difftime object for a specific number of units make_difftime(day=31) # create an interval object, need a start , end date x <- interval(ymd("2017-01-01"), ymd("2009-08-01")) int_start(x) int_end(x) int_shift(x, duration(days=14)) #interval int_length(x) as.duration(x) x2 <- interval(ymd("2011-01-01"), ymd("2010-08-01")) int_overlaps(x,x2) # overlap in 2 intervals dds <- now() + days(1:10) int_diff(dds) as.duration(10) # numeric dur <- duration(hours = 10, minutes = 6) as.numeric(dur, "hours") as.numeric(dur, "minutes") # calculate the time interval between 2 datetime # time zones OlsonNames() meeting <- ymd_hms("2018-09-21 15:00:00", tz = "Europe/Paris") with_tz(meeting, "US/Eastern") # lubridate introduces two other time objects periods and durations. Durations allow you to precisely calculate the difference between date time objects, using specific definitions like there are 365 days in a year. Period allows the length of a year to fluctuate between 365 and 366. leap_year(2011) ## regular year no leap year ymd(20110101) + dyears(1) # add a duration year ymd(20110101) + years(1) # add a period year leap_year(2012) ## leap year ymd(20120101) + dyears(1) # last day of 2012 ymd(20120101) + years(1) # first day of 2013