change time zone in R without it returning to orig

2019-08-16 17:18发布

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?

标签: r date timezone
1条回答
迷人小祖宗
2楼-- · 2019-08-16 18:02

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).

查看更多
登录 后发表回答