sunt sunt - 1 year ago 78
R Question

How to add/subtract time from a POSIXlt time while keeping its class in R?

I am manipulating some

DateTime objects. For example I would like to add an hour: = as.POSIXlt("2010-01-09 22:00:00") = + 3600
# [1] "2010-01-09 23:00:00 EST"
# [1] "POSIXct" "POSIXt"

The thing is I want
to be a
object. I know I could use
to convert it back to
, but is there a more elegant and efficient way to achieve this?

Answer Source

Short answer: No

Long answer:

POSIXct and POSIXlt objects are two specific types of the more general POSIXt 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 a POSIXlt object, the actual function used is +.POSIXt, not one specifically for POSIXlt. Inside this function, the argument is converted into a POSIXct 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download