20

Why does the Date below change to "2014-07-07" when converted to POSIXct?

Sys.setenv(TZ='America/Sao_Paulo')
d <- as.Date("2014-07-08", format="%Y-%m-%d")
d
[1] "2014-07-08"
as.POSIXct(d)
[1] "2014-07-07 21:00:00 BRT"
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Carlos Cinelli
  • 11,354
  • 9
  • 43
  • 66

1 Answers1

24

Because as.POSIXct.Date doesn't look for a timezone (and won't pass it to .POSIXct if you specify it in ...) and Date objects are "UTC", so your POSIXct is offset from the UTC of the Date object.

It would be better to call as.POSIXct on the character string directly, if you can:

> as.POSIXct("2014-07-08", format="%Y-%m-%d")
[1] "2014-07-08 BRT"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • 5
    ...or convert the Date to `character` first: `as.POSIXct(format(d))` – GSee Oct 09 '14 at 14:03
  • Thanks, Joshua. That's strange, there is a `(...)` argument but it is not passed to `.POSIXct`, and passing a simple timezone paramater would solve this `.POSIXct(unclass(d) * 86400, tz="UTC")` – Carlos Cinelli Oct 09 '14 at 17:16
  • 1
    @CarlosCinelli: I'm not sure that solves it, because that is midnight UTC, not midnight local time. – Joshua Ulrich Oct 09 '14 at 17:19