ronencozen
ronencozen

Reputation: 2201

Convert time in hours from numeric to HMS format

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

Upvotes: 4

Views: 2536

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 388797

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"

Upvotes: 5

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

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)

Upvotes: 4

akrun
akrun

Reputation: 886938

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)

Upvotes: 4

Related Questions