Working with dates and times

Mahbubul Majumder, PhD
Oct 9, 2014

What is date?

  • Dates are just count of days from a specific origin written in a specific format
as.Date(730000, origin = '0000-01-01')
[1] "1998-09-03"
as.Date(35000, origin = '1900-01-01')
[1] "1995-10-30"
  • Julian day is the day obtained from a date based on a origin
as.POSIXlt(Sys.Date(), 'yyyy-mm-dd')
[1] "2014-10-09 UTC"
as.POSIXlt(Sys.Date(), 'yyyy-mm-dd')$yday
[1] 281

Date and time

  • Current date as the computer is set
myDate <- Sys.Date()
myDate
[1] "2014-10-09"
  • Current date and time
date()
[1] "Thu Oct  9 20:28:10 2014"
  • Generate a vector of dates incremented by 10 days (notice the last day)
myDates <- seq(myDate, length=4, by = '10 day')
myDates
[1] "2014-10-09" "2014-10-19" "2014-10-29" "2014-11-08"

Converting text to dates

  • Dates are special data types
tDate <- c("2014-10-09")
myDt <- as.Date(tDate)
myDt
[1] "2014-10-09"
  • Formatting the dates
as.Date(tDate,'%Y-%m-%d')
[1] "2014-10-09"
format(myDt,format="%B %d %Y")
[1] "October 09 2014"
  • Time zone setting
x <- .POSIXct(myDt,tz="GMT")
x
[1] "1970-01-01 04:32:32 GMT"
  • Time formatting
format(x, "%H:%M:%S")
[1] "04:32:32"
  • ? format

Case study: Boston hubway data

  • What are those peaks? Data does not know how to lie.

plot of chunk unnamed-chunk-32

Case study: Boston hubway data

plot of chunk unnamed-chunk-33

Reading assignment and references