问题
I'm looking for a way to convert decimal hours to HH:MM:SS
For instance, as input:
4.927778 hours
Desired output:
04:55:40
回答1:
You can try something like below
dh <- 4.927778
strftime(as.POSIXct(dh * 60 * 60, origin = Sys.Date(), tz = "GMT"), format = "%H:%M:%S")
## [1] "04:55:40"
回答2:
You should be able to get an idea of what you need to do -
a <- "4.927778 hours"
a <- as.numeric(gsub(x = a,pattern = " hours", replacement = ""))
h <- a%/% 1
m <- ((a%% 1)*60) %/% 1
s <- round((((a%% 1)*60) %% 1)*60,0)
paste(h,m,s,sep = ":")
#[1] "4:55:40"
回答3:
An alternative solution is to convert this to a date/time class and then format it in an appropriate way.
format(ISOdatetime(1900,1,1,0,0,0, tz="GMT") +
as.difftime(4.927778, unit="hours"), "%H:%M:%S")
回答4:
You can use sprintf()
to format the output as you wish when you have the number of hours, minutes and seconds as integers. These can be calculated using modulo (%%
) and floor()
/round()
. The number of hours can be extracted from a string very nicely using the parse_number()
function from the readr package:
library(readr)
input <- "4.927778 hours"
hrs <- parse_number(input)
hours <- floor(hrs)
minutes <- floor((hrs %% 1) * 60)
seconds <- round((((hrs %% 1) * 60) %% 1) * 60)
sprintf("%02d:%02d:%02d", hours, minutes, seconds)
The advantage of this strategy is that it still works for time differences larger than 24 hours in contrast to the solutions using strftime()
.
回答5:
This should work with negative values as well.
convertHours<-function(hours){
timeoffset<-as.numeric(as.POSIXct(format(Sys.time(), tz = "GMT")) - as.POSIXct(format(Sys.time(), tz = "")))
hoursMinutes<-ifelse(hours<0,paste0("-",strftime(as.POSIXct((abs(hours)+timeoffset) * 60 * 60, origin = Sys.Date(), tz =""), format = "%H:%M")), strftime(as.POSIXct((hours+timeoffset) * 60 * 60, origin = Sys.Date(), tz =""), format = "%H:%M"))
}
h<-1.33
hhmm<-convertHours(h)
hhmm [1] "01:19"
h<--1.33
hhmm<-convertHours(h)
hhmm [1] "-01:19"
回答6:
If you are using .net/C# you can use a little bit of date math.
var when = DateTime.UtcNow; // or any time of your choice
var later = when.AddHours(4.927778);
var span = later - when;
Console.WriteLine(span)
I see the R flag now. Perhaps this will give you a hint where to look for something similar. I don't know R.
来源:https://stackoverflow.com/questions/19721145/convert-decimal-hours-to-hhmmss