I am manipulating some POSIXlt
DateTime objects. For example I would like to add an hour:
my.lt = as.POSIXlt("2010-01-09 22:00:00")
new.lt = my.lt + 3600
new.lt
# [1] "2010-01-09 23:00:00 EST"
class(new.lt)
# [1] "POSIXct" "POSIXt"
The thing is I want new.lt
to be a POSIXlt
object. I know I could use as.POSIXlt
to convert it back to POSIXlt
, but is there a more elegant and efficient way to achieve this?
?POSIXlt
tells you that:So I guess that 3600 not being a
POSIXlt
object, there is an automatic conversion.I would stick with simple:
It's not that much of a hassle to add
as.POSIXlt
before your time operation.Short answer: No
Long answer:
POSIXct
andPOSIXlt
objects are two specific types of the more generalPOSIXt
class (not in a strictly object oriented inheritance sense, but in a quasi-object oriented implementation sense). Code freely switches between these. When you add to aPOSIXlt
object, the actual function used is+.POSIXt
, not one specifically forPOSIXlt
. Inside this function, the argument is converted into aPOSIXct
and then dealt with (added to).Additionally,
POSIXct
is the number of seconds from a specific date and time.POSIXlt
is a list of date parts (seconds, minutes, hours, day of month, month, year, day of week, day of year, DST info) so adding to that directly doesn't make any sense. Converting it to a number of seconds (POSIXct
) and adding to that does make sense.It may not be significantly more elegant, but
IMHO is more descriptive than
because the code itself documents that you're going for a "POSIX" "seq"uence incremented "by 1 hour", but it's a matter of taste. Works just fine on POSIXlt, but note that it returns a POSIXct either way. Also works for "days". See help(seq.POSIXt) for details on how it handles months, daylight savings, etc.
POSIXct
-classed objects are internally a numeric value that allows numeric calculations.POSIXlt
-objects are internally lists. Unfortunately for your desires,Ops.POSIXt
(which is what is called when you use "+") coerces to POSIXct with this code:Fortunately, if you just want to and an hour there is a handy alternative to adding 3600. Instead use the list structure and add 1 to the hour element:
This approach is very handy when you want to avoid thorny questions about DST changes, at least if you want adding days to give you the same time-of-day.
Edit (adding @sunt's code demonstrating that
Ops.POSIXlt
is careful with time "overflow".))