Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding time to POSIXct object in R

I would like to add 1 hour to a POSIXct object, but it does not support '+'.

This command:

as.POSIXct("2012/06/30","GMT")      + as.POSIXct(paste(event_hour, event_minute,0,":"), ,"%H:%M:$S") 

returns this error:

Error in `+.POSIXt`(as.POSIXct("2012/06/30", "GMT"), as.POSIXct(paste(event_hour,  :     binary '+' is not defined for "POSIXt" objects 

How can I add a few hours to a POSIXct object ?

like image 423
BlueTrin Avatar asked Aug 12 '12 12:08

BlueTrin


People also ask

What is the difference between POSIXct and POSIXt?

There are two POSIX date/time classes, which differ in the way that the values are stored internally. The POSIXct class stores date/time values as the number of seconds since January 1, 1970, while the POSIXlt class stores them as a list with elements for second, minute, hour, day, month, and year, among others.

Is there a time data type in R?

time() can be used, and you can play around a bit with the basic types to get a feel for what R is doing. The as. POSIXct and as. POSIXlt commands are used to convert the time value into the different formats.

What is the purpose of the POSIXct time format?

POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.


1 Answers

POSIXct objects are a measure of seconds from an origin, usually the UNIX epoch (1st Jan 1970). Just add the requisite number of seconds to the object:

x <- Sys.time() x [1] "2012-08-12 13:33:13 BST" x + 3*60*60 # add 3 hours [1] "2012-08-12 16:33:13 BST" 
like image 51
James Avatar answered Sep 20 '22 19:09

James