Agenda


  • get current date/time
  • understand date/time classes in R
  • date arithmetic
  • timezones & daylight savings
  • date/time formats
  • date/time parsing
  • date/time components
  • create, update & verify date/time objects
  • intervals, duration and period

Prerequisites


Resources


Current Date/Time




Function Description
Sys.Date() Current Date
lubridate::today() Current Date
Sys.time() Current Time
lubridate::now() Current Time
lubridate::am() Whether time occurs in am?
lubridate::pm() Whether time occurs in pm?
lubridate::leap_year() Check if the year is a leap year?

Your Turn


  • get current date
  • get current time
  • check whether the time occurs in am or pm?
  • check whether the following years were leap years
    • 2018
    • 2016

Case Study - Data


## # A tibble: 2,466 x 3
##    Invoice    Due        Payment   
##    <date>     <date>     <date>    
##  1 2013-01-02 2013-02-01 2013-01-15
##  2 2013-01-26 2013-02-25 2013-03-03
##  3 2013-07-03 2013-08-02 2013-07-08
##  4 2013-02-10 2013-03-12 2013-03-17
##  5 2012-10-25 2012-11-24 2012-11-28
##  6 2012-01-27 2012-02-26 2012-02-22
##  7 2013-08-13 2013-09-12 2013-09-09
##  8 2012-12-16 2013-01-15 2013-01-12
##  9 2012-05-14 2012-06-13 2012-07-01
## 10 2013-07-01 2013-07-31 2013-07-26
## # ... with 2,456 more rows

Case Study


  • extract date, month and year from Due
  • compute the number of days to settle invoice
  • compute days over due
  • check if due year is a leap year
  • check when due day in february is 29, whether it is a leap year
  • how many invoices were settled within due date
  • how many invoices are due in each quarter
  • what is the average duration between invoice date and payment date

Date/Time Classes


  • Date
  • POSIXct
  • POSIXlt

ISO 8601 Format




POSIXlt



Component Description
sec Second
min Minute
hour Hour of the day
mon Month of the year (0-11
zone Timezone
wday Day of week
mday Day of month
year Years since 1900
yday Day of year
isdst Daylight saving flag
gmtoff Offset is seconds from GMT

Your Turn


R 1.0.0 was released on 2000-02-29 08:55:23 UTC. Save it as

  • Date using character
  • Date using origin and number
  • POSIXct
  • POSIXlt and extract
    • month day
    • day of year
    • month
    • zone
  • ISODate

Date Arithmetic - Course Length




Date Arithmetic - Shift Date




Your Turn


  • compute the length of a vacation which begins on 2020-04-19 and ends on 2020-04-25
  • recompute the length of the vacation after shifting the vacation start and end date by 10 days and 2 weeks
  • compute the days to settle invoice and days overdue from the receivables.csv data set
  • compute the length of employment (only for those employees who have been terminated) from the hr-data.csv data set (use date of hire and termination)

Timezones






Daylight Savings