Convert Date to POSIXct

Car*_*lli 8 r date posixct

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"
Run Code Online (Sandbox Code Playgroud)

Jos*_*ich 13

因为as.POSIXct.Date不查找时区(.POSIXct如果您指定时区也不会将其传递给...)并且Date对象是"UTC",因此您POSIXct将偏离Date对象的UTC.

如果可以的话,最好直接调用as.POSIXct字符串:

> as.POSIXct("2014-07-08", format="%Y-%m-%d")
[1] "2014-07-08 BRT"
Run Code Online (Sandbox Code Playgroud)

  • ...或者首先将Date转换为`character`:`as.POSIXct(format(d))` (2认同)