change time zone in R without it returning to original time zone

北战南征 提交于 2020-01-06 07:14:20

问题


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?


回答1:


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 the date() extractor from lubridate which is better at respecting timezones.

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"
df$startTime <- as.POSIXct(df$startTime, tz="Etc/UTC")
attributes(df$startTime)$tzone <- "America/New_York"

as.Date(df$startTime, tz="America/New_York")
#> [1] "2018-09-27" "2018-09-28" "2018-09-30"
lubridate::date(df$startTime)
#> [1] "2018-09-27" "2018-09-28" "2018-09-30"

Created on 2018-09-25 by the reprex package (v0.2.0).



来源:https://stackoverflow.com/questions/52506071/change-time-zone-in-r-without-it-returning-to-original-time-zone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!