The vec_fmt_time() function

Let’s create a character vector of datetime values in the ISO-8601 format for the next few examples:

str_vals <- c("2022-06-13 18:36", "2019-01-25 01:08", NA)

Using vec_fmt_time() (here with the "iso-short" time style) will result in a character vector of formatted times. Any NA values remain as NA values. The rendering context will be autodetected unless specified in the output argument (here, it is of the "plain" output type).

vec_fmt_time(str_vals, time_style = "iso-short")
[1] "18:36" "01:08" NA     
#> [1] "18:36" "01:08" NA

We can choose from any of 25 different time formatting styles. Many of these styles are flexible, meaning that the structure of the format will adapt to different locales. Let’s use the "Bhms" time style to demonstrate this (first in the default locale of "en"):

vec_fmt_time(str_vals, time_style = "Bhms")
[1] "6:36:00 in the evening" "1:08:00 at night"       NA                      
#> [1] "6:36:00 in the evening" "1:08:00 at night" NA

Let’s perform the same type of formatting in the German ("de") locale:

vec_fmt_time(str_vals, time_style = "Bhms", locale = "de")
[1] "6:36:00 abends" "1:08:00 nachts" NA              
#> [1] "6:36:00 abends" "1:08:00 nachts" NA

We can always use info_time_style() to call up an info table that serves as a handy reference to all of the time_style options.

As a last example, one can wrap the time values in a pattern with the pattern argument. Note here that NA values won’t have the pattern applied.

vec_fmt_time(
  str_vals,
  time_style = "hm",
  pattern = "temps: {x}",
  locale = "fr-CA"
)
[1] "temps: 6 h 36 p.m." "temps: 1 h 08 a.m." NA                  
#> [1] "temps: 6:36 PM" "temps: 1:08 AM" NA