Chapter 11. Dates and Times

Dates and times are very common in data analysis—not least for time-series analysis. The bad news is that with different numbers of days in each month, leap years, leap seconds,[33] and time zones, they can be fairly awful to deal with programmatically. The good news is that R has a wide range of capabilities for dealing with times and dates. While these concepts are fairly fundamental to R programming, they’ve been left until now because some of the best ways of using them appear in add-on packages. As you begin reading this chapter, you may feel an awkward sensation that the code is grating on you. At this point, we’ll seek lubrication from the lubridate package, which makes your date-time code more readable.

Chapter Goals

After reading this chapter, you should:

  • Understand the built-in date classes POSIXct, POSIXlt, and Date
  • Be able to convert a string into a date
  • Know how to display dates in a variety of formats
  • Be able to specify and manipulate time zones
  • Be able to use the lubridate package

Date and Time Classes

There are three date and time classes that come with R: POSIXct, POSIXlt, and Date.

POSIX Dates and Times

POSIX dates and times are classic R: brilliantly thorough in their implementation, navigating all sorts of obscure technical issues, but with awful Unixy names that make everything seem more complicated than it really is.

The two standard date-time classes in R are POSIXct and POSIXlt. (I said the names were awful!) POSIX is a set of standards ...

Get Learning R now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.