Skip to contents

dttm_ functions help in the manipulation of date and datetime variables.

dttm_diff

The goal of dttm_diff is to compute the difference between two dates.

date1 <- lubridate::dmy("01/05/1998")

date2 <- lubridate::dmy("21/11/2018")

dttm_diff(date1 = date1,date2 = date2,unit = "days")
#> [1] 7509

So the time difference between 21/11/2018 and 01/05/1998 is 7,509 days.

If you need to add a constant to your difference, use the add argument.

dttm_diff(date1 = date1,date2 = date2,unit = "days",add = 1)
#> [1] 7510

dttm_vars

The goal of dttm_vars is to compute variables derived from date, such as year, month, day, etc.

dt <- seq(as.Date("1910/1/1"), as.Date("1911/1/1"), "days")

df_dt <- data.frame(dt = dt)

dttm_vars(df_dt,dt) %>% dplyr::glimpse()
#> Rows: 366
#> Columns: 12
#> $ dt          <date> 1910-01-01, 1910-01-02, 1910-01-03, 1910-01-04, 1910-01-0…
#> $ mon_abb     <ord> Jan, Jan, Jan, Jan, Jan, Jan, Jan, Jan, Jan, Jan, Jan, Jan…
#> $ mon_lbl     <ord> January, January, January, January, January, January, Janu…
#> $ mon_num     <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
#> $ day_num     <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,…
#> $ year_num    <dbl> 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910…
#> $ year_lbl    <fct> 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910, 1910…
#> $ week_num    <dbl> 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3…
#> $ epiweek_num <dbl> 52, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, …
#> $ isoweek_num <dbl> 52, 52, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3,…
#> $ wday_abb    <ord> Sat, Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun, Mon, Tue, Wed…
#> $ wday_lbl    <ord> Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Fr…

The new variables respective to the date are:

  • mon_abb: a factor with the abbreviated name of the month;
  • mon_lbl: a factor with the complete name of the month;
  • mon_num: the number of the month;
  • day_num: the number of the day within the month;
  • year_num: the number of the year;
  • year_lbl: the number of the year, as a factor;
  • week_num: the number of complete seven day periods that have occurred between the date and January 1st, plus one;
  • epiweek_num: the US CDC version of epidemiological week. Starts on Sunday;
  • isoweek_num: the week as it would appear in the ISO 8601 system, which uses a reoccurring leap week. Starts on Monday;
  • wday_abb: a factor with the week day abbreviated name;
  • wday_lbl: a factor with the week day complete name.