3 Dates and Times

3.1 Prerequisites

In this chapter, we will introduce the lubridate package that is designed to make it easier to work with dates and times in R.

3.2 Parsing dates and times

You can easily transform dates and times stored as character vectors to Date or POSIXct (or date-time) objects in R using lubridate. All you need to do is specify the order of the year y, month m, and the day d and lubridate will automatically figure out the format.

dmy("3/12/1985")
## [1] "1985-12-03"
ymd("85/12/03")
## [1] "1985-12-03"
mdy("Dec 3rd 1985")
## [1] "1985-12-03"
ydm("85-3rd-december")
## [1] "1985-12-03"

The same functions can also convert numeric vectors.

ymd(19851203)
## [1] "1985-12-03"
dmy(31285)
## [1] "1985-12-03"

You can create Date objects with the time component using a POSIXct or date-time object simply by adding an underscore followed by the order of the hour h, minute m and second s.

ymd_h("1985/12/03 21")
## [1] "1985-12-03 21:00:00 UTC"
ymd_hm("1985/12/03 21:05")
## [1] "1985-12-03 21:05:00 UTC"
ymd_hms("1985/12/03 21:05:30")
## [1] "1985-12-03 21:05:30 UTC"

You can also specify the time zone by providing inputs to the argument tz. You can find out more about time zones in R by typing ?timezones into the console.

ymd_hms("1985/12/03 21:05:30", tz = "Singapore")
## [1] "1985-12-03 21:05:30 +08"

Date vs date-time objects that are created using lubridate. By default, dates will be created as Date objects without the time component. You can force the creation of a date-time object by including the timezone tz argument.

class(ymd("1985/12/03"))
## [1] "Date"
class(ymd("1985/12/03", tz = "Singapore"))
## [1] "POSIXct" "POSIXt"
class(ymd_hms("1985/12/03 21:05:30"))
## [1] "POSIXct" "POSIXt"

3.3 Extracting components

lubridate provides simple functions that allows you to easily get different components of a date or date-time object. These functions are especially useful when analyzing time-series data and when you want to group your data by a particular time period.


my_dt <- ymd_hms("1985/12/03 21:05:30")
year(my_dt)
## [1] 1985
month(my_dt)
## [1] 12
day(my_dt)
## [1] 3
hour(my_dt)
## [1] 21
minute(my_dt)
## [1] 5
second(my_dt)
## [1] 30
wday(my_dt, label = TRUE)
## [1] Tue
## Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat