Day 15: hms

A simple class for durations or time-of-day values, hms lets you construct and work with hours, minutes, and seconds.

Published

December 15, 2022

Dates get a lot of hype, but sometimes what you’re concerned about is time of the hours-minutes-seconds variety, which is where hms (Müller 2022) comes to play. Though it has a handful of different functions, the crux of the hms package is the class that it provides for storing durations or time-of-day values, and displaying them in the hh:mm:ss format.

The hms class is based on the difftime class, and, like difftime data are stored as number of seconds since midnight (00:00:00). Thus, values can be converted to and from numeric with as.numeric() and as_hms().

Below, we’ll use parse_hms() (which accepts values as HH:MM:SS—and can include optional fractional seconds) to create hms values, look at their underlying numeric representation with as.numeric(), and then complete the round trip with as_hms().

library(hms)

# text to hms
times <- parse_hms(c("00:00:00.75", "00:00:05", "00:01:00", "01:00:00"))
times
#> 00:00:00.75
#> 00:00:05.00
#> 00:01:00.00
#> 01:00:00.00

# hms to numeric
times_num <- as.numeric(times)
times_num
#> [1]    0.75    5.00   60.00 3600.00

# numeric to hms
as_hms(times_num)
#> 00:00:00.75
#> 00:00:05.00
#> 00:01:00.00
#> 01:00:00.00

You can also do coercion to and from types, such as POSIXct.

as.POSIXct(hms(1))
#> [1] "1970-01-01 00:00:01 UTC"

Note that, above, I’ve used the titular function hms(), which allows you to construct hms values from their component seconds, minutes, and hours. By position, the arguments go smallest to largest (from seconds to hours), but can also be named and/or include a day argument1.

  • 1 Days will be converted to seconds (like any hms value), and displayed in normal hms format, ##:##:##.##.

  • hms(30, 20, 1)
    #> 01:20:30
    
    hms(hours = 1, minutes = 20, seconds = 30)
    #> 01:20:30
    
    hms(hours = 1, minutes = 20, seconds = 30, days = 4)
    #> 97:20:30

    Learn more

    You can learn more about hms in the package documentation. If you’re interested in datetimes, check out lubridate or clock.

    References

    Müller, Kirill. 2022. hms: Pretty Time of Day. https://hms.tidyverse.org.