The hms package provides a simple class for storing durations or time-of-day values and displaying them in the hh:mm:ss format. This class is intended to simplify data exchange with databases, spreadsheets, and other data sources:
POSIXt
difftime
class"digits.secs"
option# The easiest way to get hms is to install the whole tidyverse:
install.packages("tidyverse")
# Alternatively, install just hms:
install.packages("hms")
# Or the the development version from GitHub:
# install.packages("pak")
::pak("tidyverse/hms") pak
The following example showcases ways of using the hms
class standalone or as a data frame column.
library(hms)
hms(56, 34, 12)
#> 12:34:56
as_hms(Sys.time())
#> 10:27:38.905625
parse_hms("12:34:56")
#> 12:34:56
as.POSIXct(hms(1))
#> [1] "1970-01-01 00:00:01 UTC"
data.frame(hours = 1:3, hms = hms(hours = 1:3))
#> hours hms
#> 1 1 01:00:00
#> 2 2 02:00:00
#> 3 3 03:00:00
Objects of the hms
and its underlying
difftime
classes are stored as number of seconds since
00:00:00
. Use as.numeric()
and
as_hms()
to convert to and from numbers.
<- parse_hms(c("00:00:00.25", "00:00:01", "00:01:30", "01:00:00"))
times
times#> 00:00:00.25
#> 00:00:01.00
#> 00:01:30.00
#> 01:00:00.00
<- as.numeric(times)
times_num
times_num#> [1] 0.25 1.00 90.00 3600.00
as_hms(times_num)
#> 00:00:00.25
#> 00:00:01.00
#> 00:01:30.00
#> 01:00:00.00
Please note that the ‘hms’ project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.