Convert Date to POSIXct
Asked Answered
O

1

22

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"
Oviposit answered 9/10, 2014 at 13:29 Comment(4)
Could this be related to the time zone? What if you supply a specific time zone when calling as.POSIXct(d, tz = "...")?Banky
@beginneR I wanted to know the reason why that happens, I already have a workaround.Oviposit
Maybe because of this (from ?as.POSIXct): "Dates without times are treated as being at midnight UTC."Banky
What is a fromat? :)Auden
A
26

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"
Auden answered 9/10, 2014 at 14:2 Comment(3)
...or convert the Date to character first: as.POSIXct(format(d))Rufford
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")Oviposit
@CarlosCinelli: I'm not sure that solves it, because that is midnight UTC, not midnight local time.Auden

© 2022 - 2024 — McMap. All rights reserved.