[R] generating a sequence of seconds

John McKown john.archie.mckown at gmail.com
Tue Aug 12 21:40:26 CEST 2014


On Tue, Aug 12, 2014 at 1:51 PM, Erin Hodgess <erinm.hodgess at gmail.com> wrote:
> Hello!
>
> If I would like to generate a sequence of seconds for a date, I would do
> the following:
>
> x <- seq(from=as.POSIXct(2014-08-12 00:00:00),to=as.POSIXct(2014-08-12
> 23:59:59),by="secs")
>
> What if I just want the seconds vector without the date, please?  Is there
> a convenient way to create such a vector, please?
>
> thanks,
> Erin
>
>
> --
> Erin Hodgess

I'm a bit confused by this request. The definition of a POSIXct is:
Class "POSIXct" represents the (signed) number of seconds since the
beginning of 1970 (in the UTC time zone) as a numeric vector.

So I don't really know what you mean by the "seconds portion". There
are 24*60*60 or 86,400 seconds in a day. Those seconds are from +0 at
00:00:00 to +86399 for 23:59:59. Is this what you were asking?

seconds_vector <-0:86399; #is the simple way to get the above.

By the definition given above, there is no such thing as a POSIXct
value without a date portion. Any number value will convert to a
date+time. Like a timestamp variable in SQL vs. a time variable.

If you want to display the seconds_vector as "HH:MM:SS" for some
reason, the simple way is:

character_time=sprintf("%02d:%02d:%02d", # C-style formatting string
                                 seconds_vector/3600, # hour value
                                 (seconds_vector%%3600)/60, #minute value
                                 seconds_vector%%60); #second value

You can simply make that a function

getTimePortion <- function(POSIXct_value) {
                            value_in_seconds=as.integer(POSIXct_value);
                            sprintf("%02d:%02d:%02d", # C-style
formatting string
                                     seconds_vector/3600, # hour value
                                     (seconds_vector%%3600)/60, #minute value
                                     seconds_vector%%60); #second value
                  };

-- 
There is nothing more pleasant than traveling and meeting new people!
Genghis Khan

Maranatha! <><
John McKown



More information about the R-help mailing list