[R] Minutes after midnight to time

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sat Dec 14 05:36:04 CET 2013


On Fri, 13 Dec 2013, Trevor Davies wrote:

> Is there a quick function that can convert minutes (seconds) after midnight
> to a time?
>
> i.e 670.93 (minutes after midnight) --> 11:10:56.**
>
> I know it can be done by hand but I thought there must be a function for
> this already.

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".

> Thank you.
>
> 	[[alternative HTML version deleted]]

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



More information about the R-help mailing list