The fmt_datetime() function

Use the exibble dataset to create a single-column gt table (with only the datetime column). With fmt_datetime() we’ll format the datetime column to have dates formatted with the "month_day_year" style and times with the "h_m_s_p" 12-hour time style.

exibble |>
  dplyr::select(datetime) |>
  gt() |>
  fmt_datetime(
    date_style = "month_day_year",
    time_style = "h_m_s_p"
  )
datetime
January 1, 2018 2:22:00 AM
February 2, 2018 2:33:00 PM
March 3, 2018 3:44:00 AM
April 4, 2018 3:55:00 PM
May 5, 2018 4:00:00 AM
June 6, 2018 4:11:00 PM
July 7, 2018 5:22:00 AM
NA

Using the same input table, we can use fmt_datetime() with flexible date and time styles. Two that work well together are "MMMEd" and "Hms". These date and time styles will, being flexible, create outputs that conform to the locale value given to the locale argument. Let’s use two calls of fmt_datetime(): the first will format all rows in datetime to the Danish locale (with locale = "da") and the second call will target the first three rows with the same formatting, but in the default locale (which is "en").

exibble |>
  dplyr::select(datetime) |>
  gt() |>
  fmt_datetime(
    date_style = "MMMEd",
    time_style = "Hms",
    locale = "da"
  ) |>
  fmt_datetime(
    rows = 1:3,
    date_style = "MMMEd",
    time_style = "Hms"
  )
datetime
Mon, Jan 1 02:22:00
Fri, Feb 2 14:33:00
Sat, Mar 3 03:44:00
ons 4. apr. 15.55.00
lør 5. maj 04.00.00
ons 6. jun. 16.11.00
lør 7. jul. 05.22.00
NA

It’s possible to use the format argument and write our own formatting specification. Using the CLDR datetime pattern "EEEE, MMMM d, y 'at' h:mm a (zzzz)" gives us datetime outputs with time zone formatting. Let’s provide a time zone ID ("America/Vancouver") to the tz argument.

exibble |>
  dplyr::select(datetime) |>
  gt() |>
  fmt_datetime(
    format = "EEEE, MMMM d, y 'at' h:mm a (zzzz)",
    tz = "America/Vancouver"
  )
datetime
Monday, January 1, 2018 at 2:22 AM (Pacific Standard Time)
Friday, February 2, 2018 at 2:33 PM (Pacific Standard Time)
Saturday, March 3, 2018 at 3:44 AM (Pacific Standard Time)
Wednesday, April 4, 2018 at 3:55 PM (Pacific Daylight Time)
Saturday, May 5, 2018 at 4:00 AM (Pacific Daylight Time)
Wednesday, June 6, 2018 at 4:11 PM (Pacific Daylight Time)
Saturday, July 7, 2018 at 5:22 AM (Pacific Daylight Time)
NA