Intervals

Working with Dates and Times in R

Charlotte Wickham

Instructor

Creating intervals

datetime1 %--% datetime2, or
interval(datetime1, datetime2)

dmy("5 January 1961") %--% dmy("30 January 1969")
1961-01-05 UTC--1969-01-30 UTC
interval(dmy("5 January 1961"), dmy("30 January 1969"))
1961-01-05 UTC--1969-01-30 UTC
Working with Dates and Times in R

Operating on an interval

beatles <- dmy("5 January 1961") %--% dmy("30 January 1969")

int_start(beatles)
"1961-01-05 UTC"
int_end(beatles)
"1969-01-30 UTC"
Working with Dates and Times in R

Operating on an interval

int_length(beatles)
254620800
as.period(beatles)
"8y 0m 25d 0H 0M 0S"
as.duration(beatles)
"254620800s (~8.07 years)"
Working with Dates and Times in R

Comparing intervals

hendrix_at_woodstock <- mdy("August 17 1969")
hendrix_at_woodstock %within% beatles
FALSE
hendrix <- dmy("01 October 1966") %--% dmy("16 September 1970")
int_overlaps(beatles, hendrix)
TRUE
Working with Dates and Times in R

Which kind of time span?

Use:

  • Intervals when you have a start and end
  • Periods when you are interested in human units
  • Durations if you are interested in seconds elapsed
Working with Dates and Times in R

Monarchs of England

Monarchs of Britain

monarchs
# A tibble: 131 x 4
                              name       from         to       dominion
                             <chr>     <dttm>     <dttm>          <chr>
 1                    Elizabeth II 1952-02-06 2017-10-07 United Kingdom
 2                        Victoria 1837-06-20 1901-01-22 United Kingdom
 3                        George V 1910-05-06 1936-01-20 United Kingdom
 4                      George III 1801-01-01 1820-01-29 United Kingdom
# ... with 127 more rows
Working with Dates and Times in R

Halley's comet

Halley's comet: https://en.wikipedia.org/wiki/Halley%27s_Comet#Apparitions

halleys
# A tibble: 27 x 6
      designation  year perihelion_date start_date   end_date distance
            <chr> <int>          <date>     <date>     <date>    <chr>
 1   1P/66 B1, 66    66      0066-01-26 0066-01-25 0066-01-26     <NA>
 2 1P/141 F1, 141   141      0141-03-25 0141-03-22 0141-03-25     <NA>
 3 1P/218 H1, 218   218      0218-04-06 0218-04-06 0218-05-17     <NA>
 4 1P/295 J1, 295   295      0295-04-07 0295-04-07 0295-04-20     <NA>
# ... with 23 more rows
Working with Dates and Times in R

Let's practice!

Working with Dates and Times in R

Preparing Video For Download...