Chapter 13 Dates and times

13.1 Date-time vectors: where they fit in

We’ve spent a lot of time working with big, beautiful data frames. That are clean and wholesome, like the Gapminder data. With crude temporal information like, “THE YEAR IS 1952”.

But real life will be much nastier. This information will come to you with much greater precision, reported to the last second or worse, complicated by time zones and daylight savings time idiosyncrasies. Or in some weird format.

Here we discuss common remedial tasks for dealing with date-times.

13.2 Resources

I start with this because we cannot possibly do this topic justice in a short amount of time. Our goal is to make you aware of specific problems and solutions. Once you have a character problem in real life, these resources will be extremely helpful as you delve deeper.

Dates and times chapter from R for Data Science by Hadley Wickham and Garrett Grolemund (2016). See also the subsection on dates and times in the Data import chapter.

The lubridate package (CRAN; GitHub; main vignette).

Grolemund and Wickham’s paper on lubridate in the Journal of Statistical Software (2011).

Exercises to push you to learn lubridate: part 1, part 2, and part 3 posts include links to answers!

13.3 Load the tidyverse and lubridate

13.4 Get your hands on some dates or date-times

Use base Sys.Date() or lubridate’s today() to get today’s date, without any time.

They both give you something of class Date.

Use base Sys.time() or lubridate’s now() to get RIGHT NOW, meaning the date and the time.

They both give you something of class POSIXct in R jargon.

13.5 Get date or date-time from character

One of the main ways dates and date-times come into your life:

http://r4ds.had.co.nz/dates-and-times.html#creating-datetimes#from-strings

13.6 Build date or date-time from parts

Second most common way dates and date-times come into your life:

http://r4ds.had.co.nz/dates-and-times.html#creating-datetimes#from-individual-components

Once you have dates, you might want to edit them in a non-annoying way:

http://r4ds.had.co.nz/dates-and-times.html#setting-components

13.8 Arithmetic with date or date-time

http://r4ds.had.co.nz/dates-and-times.html#time-spans

13.9 Get character from date or date-time

Eventually you will need to print this stuff in, say, a report.

I always use format() but assumed lubridate had something else/better. Am I missing something here? Probably. For now, read the help: ?format.POSIXct.