[R] date and time coding question

MacQueen, Don macqueen1 at llnl.gov
Thu May 16 17:22:40 CEST 2013

The difftime() function has a units argument, so it seems kind of obvious
to me to think of objects of class 'difftime' as having units. And indeed
they do, stored as an attribute:

> str(difftime( Sys.time()+3700, Sys.time(), units='min'))
Class 'difftime'  atomic [1:1] 61.7
  ..- attr(*, "units")= chr "mins"

> str(difftime( Sys.time()+3700, Sys.time(), units='sec'))
Class 'difftime'  atomic [1:1] 3700
  ..- attr(*, "units")= chr "secs"

The numeric values are already in the specified units, prior to any
printing or other further use of the result.

?difftime says,

If 'units = "auto"', a suitable set of units is chosen, the
largest possible (excluding '"weeks"') in which all the absolute
differences are greater than one.

-end quote-

So it's pretty clear that the units are chosen when the difference is
calculated, not later. Inspection of the difftime() function source code
confirms this. One can also inspect print.difftime() and see that the
numeric value is used as is, without any unit conversion.

Which returns me to my original point: when using diff() on a POSIXt
object, I don't know how to specify the units, whereas with difftime() I
do. If there is a way to specify units using diff(), I'd love to know
about it!


Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550

On 5/15/13 8:57 PM, "Jeff Newmiller" <jdnewmil at dcn.davis.CA.us> wrote:

>The difference of two POSIXct values is of type difftime. You should not
>think of difftime as having units. Rather, you should think of the result
>of converting from difftime to numeric (using as.numeric) as the
>opportunity (or rather requirement) to specify what time units you want.
>If you let R print the difftime object unconverted, it will print with
>whatever units seem appropriate given the magnitude of the difftime.
>Jeff Newmiller                        The     .....       .....  Go
>DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live
>                                      Live:   OO#.. Dead: OO#..  Playing
>Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
>/Software/Embedded Controllers)               .OO#.       .OO#.
>Sent from my phone. Please excuse my brevity.
>"MacQueen, Don" <macqueen1 at llnl.gov> wrote:
>>I think you probably want
>>   format='%m/%d/%y %H:%M')
>>(lower case "y")
>>diff() as suggested by Jeff Newmiller is good, except that I don't know
>>how to control the units using diff().
>>## so a method that allows specifying units other than hours would be,
>>datetime <-c("1/1/13 00:00","1/1/13 12:00","1/2/13 00:00","1/2/13
>>datetime <-as.POSIXct(datetime,format='%m/%d/%y %H:%M')deltas <-
>>datetime[-1], datetime[-length(datetime)] , units='min')

More information about the R-help mailing list