I have a df with dates and times like this:
df <- data.frame(c("2018-09-28 00:00:00Z","2018-09-29 01:00:00Z","2018-09-30 10:00:00Z"))
names(df) <- "startTime"
The dates and times are in UTC time zone, so I format like this:
df$startTime <- as.POSIXct(df$startTime, tz="Etc/UTC")
I then want to put them in New York time, like this:
attributes(df$startTime)$tzone <- "America/New_York"
Now I want to extract just the date using as.Date. Unfortunately, the code below returns the dates to the UTC time zone. Notice how when you run the code below, the dates that were before midnight New York time changed to their post-midnight UTC time dates.
df$startTime <- as.Date(df$startTime)
Why does this happen, and how can I maintain the time zone that I want?
as.Date
unfortunately defaults to UTC as noted in the documentation, so you can manually specify the timezone to get it to work. Alternatively, you can use thedate()
extractor fromlubridate
which is better at respecting timezones.Created on 2018-09-25 by the reprex package (v0.2.0).