# 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

library(tidyverse)
library(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.

Sys.Date()
#> [1] "2019-10-14"
today()
#> [1] "2019-10-14"

They both give you something of class Date.

str(Sys.Date())
#>  Date[1:1], format: "2019-10-14"
class(Sys.Date())
#> [1] "Date"
str(today())
#>  Date[1:1], format: "2019-10-14"
class(today())
#> [1] "Date"

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

Sys.time()
#> [1] "2019-10-14 18:05:41 UTC"
now()
#> [1] "2019-10-14 18:05:41 UTC"

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

str(Sys.time())
#>  POSIXct[1:1], format: "2019-10-14 18:05:41"
class(Sys.time())
#> [1] "POSIXct" "POSIXt"
str(now())
#>  POSIXct[1:1], format: "2019-10-14 18:05:41"
class(now())
#> [1] "POSIXct" "POSIXt"

## 13.5 Get date or date-time from character

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

## 13.6 Build date or date-time from parts

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

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

## 13.7 Get parts from date or date-time

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