Skip to content

Minutes after midnight to time

4 messages · Trevor Davies, Ben Tupper, Jeff Newmiller +1 more

#
Hi,
On Dec 13, 2013, at 4:34 PM, Trevor Davies <davies.trevor at gmail.com> wrote:

            
I'm not sure what you mean by doing it by hand, but do the following do the trick for you?

# convert seconds to hours
s2h <- function(x=670.93*60) {
   h <- floor(x/3600)
   m <- floor((x - h*3600)/60)
   s <- x - h*3600 - m*60
   sprintf("%0.2d:%0.2d:%6.3f", h, m, s)

}
# convert minutes to hours
m2h <- function(x=670.93) {
   h <- floor(x/60)
   m <- floor(x - h*60)
   s <- (x - h*60 - m) * 60
   sprintf("%0.2d:%0.2d:%6.3f", h, m, s)
}
[1] "11:10:55.800"
[1] "11:10:55.800"

Cheers,
Ben
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org
#
On Fri, 13 Dec 2013, Trevor Davies wrote:

            
Sort of.  There isn't really a "time-of-day" datatype in R in the way you 
are thinking about it, so naturally there are no functions associated with 
that data type. (This is actually how Excel does it also.) There is the 
difftime data type, but it does not print to your desired format.

However, you can ignore the date portion of a POSIXt type:

strftime( as.POSIXct( "1970-01-01" ) + as.difftime( 670.93, units="mins" 
), "%H:%M:%OS3" )

[1] "11:10:55.799"

However, this is not a particularly computationally efficient route to 
your goal (a large vector of minutes values converts quickly to difftime, 
and that adds quickly to the POSIXct value, but then strftime converts it 
to POSIXlt for putting pieces into the string which is not so "quick"), so 
if you are looking for "quick" execution you might want to go ahead and do 
it, as you say, "by hand".

On the other hand, I find it quite "quick" to remember how to do this, so 
in that sense it could be described as "quick".
Per the Posting Guide, please don't post in HTML.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
#
On Dec 13, 2013, at 1:34 PM, Trevor Davies wrote:

            
format( as.POSIXct(Sys.Date()) + 670.93*60,
        format="%H:%M:%S", tz="UCT")

[1] "11:10:55"
David Winsemius
Alameda, CA, USA