5

I have a list of dates that I was trying to use Reduce on and realized that the hours were being changed when I combined the vectors. Here's an example:

x = structure(1315714440, tzone = "UTC", class = c("POSIXct", "POSIXt"))
y = structure(1325832660, tzone = "UTC", class = c("POSIXct", "POSIXt"))
x
[1] "2011-09-11 04:14:00 UTC"
y
[1] "2012-01-06 06:51:00 UTC"
c(x,y)
[1] "2011-09-11 00:14:00 EDT" "2012-01-06 01:51:00 EST"

Why is this happening? Any suggestions on alternatives?

Thanks!

Henrik
  • 65,555
  • 14
  • 143
  • 159
svenhalvorson
  • 1,090
  • 8
  • 21
  • I found an old work-around using `rbind()` on the R mailing list [here](https://stat.ethz.ch/pipermail/r-help/2006-September/113895.html), in an attempt to avoid having to re-assign the time zone. – aosmith Oct 05 '18 at 16:39

1 Answers1

5

c.POSIXct removes the time zone attribute. From ?c.POSIXct:

Using c [...] on "POSIXct" objects drops any "tzone" attributes (even if they are all marked with the same time zone).

Thus, following your c(x,y), you may restore the original UTC time zone using attr:

xy <- c(x, y)
attr(xy, "tzone") <- "UTC"
xy
# [1] "2011-09-11 04:14:00 UTC" "2012-01-06 06:51:00 UTC" 

More background by Ripley here:

c(a, b) for POSIXct objects with tzone attributes?

"We considered having c() retain the timezone if it was common to all the objects, but the main issue was that c() was documented to remove attributes:

c is sometimes used for its side effect of removing attributes except names, for example to turn an array into a vector. as.vector is a more intuitive way to do this, but also drops names. Note too that methods other than the default are not required to do this (and they will almost certainly preserve a class attribute).

So, sometimes removing and sometimes retaining attributes was going to be confusing.

But in any case, the documentation (?c.POSIXct) is clear:

Using c on "POSIXlt" objects converts them to the current time zone, and on "POSIXct" objects drops any "tzone" attributes (even if they are all marked with the same time zone).

So the recommended way is to add a "tzone" attribute if you know what you want it to be. POSIXct objects are absolute times: the timezone merely affects how they are converted (including to character for printing)."


As noted by @aosmith, rbind can be used as work-around:

how to retain time zone when doing c(POSIXct)

Henrik
  • 65,555
  • 14
  • 143
  • 159