Reputation: 475
I have a vector of decimal numbers, which represent 'decimal day', the fraction of a day. I want to convert it into HH:MM format using R.
For example, the number 0.8541667
would correspond to 20:30
. How can I convert the numbers to HH:MM
format?
Upvotes: 14
Views: 7354
Reputation: 501
If you are converting the decimals in a dataframe and there are NULL
s in the column, times
function from library(chron)
is throwing an error. Alternatively, you can use library(openxlsx)
and library(hms)
.
library(openxlsx)
library(hms)
time <- 0.8541667
time1 <- convertToDateTime(time)
time2 <- as_hms(format(time1, "%H:%M:%S"))
Upvotes: 0
Reputation: 66819
One option with data.table:
> library(data.table)
> structure(as.integer(0.4305556*60*60*24), class="ITime")
[1] "10:20:00"
We convert from day fraction to seconds since midnight; coerce to integer; and apply ITime class. (ITime works with integer-stored seconds since midnight.)
Other resources:
Upvotes: 2
Reputation: 368211
Try this:
R> format(as.POSIXct(Sys.Date() + 0.8541667), "%H:%M", tz="UTC")
[1] "20:30"
R>
We start with a date--which can be any date, so we use today--and add your desired fractional day.
We then convert the Date type into a Datetime object.
Finally, we format the hour and minute part of the Datetime object, ensuring that UTC is used for the timezone.
Upvotes: 15