4

How to convert numbers that represent time in hours from numeric to HMS format.

for example:

8.0 -> 08:00:00
0.5 -> 00:30:00
0.25 -> 00:15:00
Henrik
  • 65,555
  • 14
  • 143
  • 159
ronencozen
  • 1,991
  • 1
  • 15
  • 26
  • Does this answer your question? [How to convert decimal time to time format](https://stackoverflow.com/questions/46167536/how-to-convert-decimal-time-to-time-format) – Limey Aug 06 '20 at 07:40
  • Can you please specify the `class` of the desired output - is it `character` or a dedicated time class? If the latter, you have `data.table::as.ITime(x*3600)`. – Henrik Aug 06 '20 at 12:38
  • ...or `chron::times(x/24)`. – Henrik Aug 06 '20 at 12:56
  • [Convert decimal hours to HH:MM:SS](https://stackoverflow.com/questions/19721145/convert-decimal-hours-to-hhmmss) – Henrik Aug 06 '20 at 13:41

3 Answers3

5

Convert to seconds, make use of seconds_to_periods from lubridate and change it to hms

hms::hms(lubridate::seconds_to_period(floor(v1 * 60 *60)))
#08:00:00
#00:30:00
#00:15:00

data

v1 <- c(8, 0.5, 0.25)
akrun
  • 874,273
  • 37
  • 540
  • 662
5

Here is a base R option

h <- x%/%1
m <- floor(x%%1 * 60)
s <- round((x%%1 * 60)%%1*60)
sprintf("%02d:%02d:%02d",h,m,s)

such that

> sprintf("%02d:%02d:%02d",h,m,s)
[1] "08:00:00" "00:30:00" "00:15:00" "03:45:22"

Data

x <- c(8.0,0.5,0.25,3.756)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
5

Another base R option :

x <- c(8, 0.5, 0.25)
format(as.POSIXct(x * 3600, origin = '1970-01-01', tz = 'UTC'), '%T')
#[1] "08:00:00" "00:30:00" "00:15:00"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213