Convert Date to POSIXct

21,766

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"
Share:
21,766
Carlos Cinelli
Author by

Carlos Cinelli

Economist/Statistician.

Updated on August 04, 2020

Comments

  • Carlos Cinelli
    Carlos Cinelli almost 4 years

    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"
    
  • GSee
    GSee over 9 years
    ...or convert the Date to character first: as.POSIXct(format(d))
  • Carlos Cinelli
    Carlos Cinelli over 9 years
    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")
  • Joshua Ulrich
    Joshua Ulrich over 9 years
    @CarlosCinelli: I'm not sure that solves it, because that is midnight UTC, not midnight local time.