---
title: "Dates and Times | r4ds Chapter 16"
date: "Jan 25, 2022"
subtitle: Biostat 203B
output:
  # ioslides_presentation: default
  html_document:
    toc: true
    toc_depth: 4
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r}
library(tidyverse)
library(lubridate)
library(nycflights13)
```

## Basics

Three types of data/time data:  

- **date**. Tibbles print it as `<date>`.  
- **time**. Tibbles print it as `<time>`.  
- **date-time**. Tibbles print it as `<dttm>`.  

In the `flights` tibble, the last variable `time_hour` is in the data-time format:
```{r}
flights %>% print(width = Inf)
```

## Create date/times

Today:
```{r}
# current date
today()
# current date-time
now()
```

### From strings

```{r}
ymd("2020-01-30")
mdy("January 30th, 2020")
dmy("30-Jan-2020")
```
```{r}
ymd_hms("2020-01-30 14:57:25")
ymd_hm("2020-01-30 14:57")
```

### From unquoated numbers

```{r}
ymd(20200130)
```

### From variables/columns in a tibble

```{r}
flights %>% 
  select(year, month, day, hour, minute) %>%
  mutate(departure = make_datetime(year, month, day, hour, minute))
```

```{r}
make_datetime_100 <- function(year, month, day, time) {
  make_datetime(year, month, day, time %/% 100, time %% 100)
}

flights_dt <- flights %>% 
  filter(!is.na(dep_time), !is.na(arr_time)) %>% 
  mutate(
    dep_time = make_datetime_100(year, month, day, dep_time),
    arr_time = make_datetime_100(year, month, day, arr_time),
    sched_dep_time = make_datetime_100(year, month, day, sched_dep_time),
    sched_arr_time = make_datetime_100(year, month, day, sched_arr_time)
  ) %>% 
  select(origin, dest, ends_with("delay"), ends_with("time")) %>%
  print(width = Inf)
```
Now we can visualize the distribution of departure times across the year  
```{r}
flights_dt %>% 
  ggplot(aes(x= dep_time)) + 
  geom_freqpoly(binwidth = 86400) # 86400 seconds = 1 day
```
or within a single day:
```{r}
flights_dt %>% 
  filter(dep_time < ymd(20130102)) %>% 
  ggplot(aes(dep_time)) + 
  geom_freqpoly(binwidth = 600) # 600 s = 10 minutes
```

## Getting components

```{r}
datetime <- ymd_hms("2020-01-30 15:34:56")
year(datetime)
month(datetime)
mday(datetime)
yday(datetime)
wday(datetime)
```
More information in `month()` and `wday()`:
```{r}
month(datetime, label = TRUE, abbr = FALSE)
wday(datetime, label = TRUE, abbr = FALSE)
```
Visualize number of departures during a week:
```{r}
flights_dt %>% 
  mutate(wday = wday(dep_time, label = TRUE)) %>% 
  ggplot(aes(x = wday)) +
  geom_bar()
```

## Rounding

`floor_date()`, `round_date()`, `ceiling_date()`:
```{r}
flights_dt %>% 
  count(week = floor_date(dep_time, "week")) %>% 
  ggplot(aes(x = week, y = n)) +
  geom_line()
```

## Time spans

### Durations

Substract two dates we get a `difftime` object:
```{r}
# How old is Hadley?
h_age <- today() - ymd(19791014)
h_age
```
lubridate provides the **duration** object that always uses seconds:
```{r}
as.duration(h_age)
```

Constructors for duration:
```{r}
dseconds(5)
dminutes(10)
dhours(c(12, 24))
ddays(0:5)
dweeks(3)
dyears(1)
```

### Periods

Durations represent an exact number of seconds:
```{r}
one_pm <- ymd_hms("2016-03-12 13:00:00", tz = "America/New_York")
one_pm
one_pm + ddays(1)
```

Periods are time spans but don’t have a fixed length in seconds, instead they work with “human” times, like days and months.
```{r}
one_pm
one_pm + days(1)
```

Constructors for period:
```{r}
seconds(15)
minutes(10)
hours(c(12, 24))
days(7)
months(1:6)
weeks(3)
years(1)
```

Some planes appear to have arrived at their destination before they departed from New York City.
```{r}
flights_dt %>% 
  filter(arr_time < dep_time) %>%
  print(width = Inf)
```
These are the overnight flights. Let's fix this:
```{r}
flights_dt <- flights_dt %>% 
  mutate(
    overnight = arr_time < dep_time,
    arr_time = arr_time + days(overnight * 1),
    sched_arr_time = sched_arr_time + days(overnight * 1)
  )


### Intervals


