更改R中的时区,但不返回原始时区 [英] change time zone in R without it returning to original time zone

查看:48
本文介绍了更改R中的时区,但不返回原始时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期和时间类似的df:

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"

日期和时间位于UTC时区,因此我采用以下格式:

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"

现在我只想使用as.Date提取日期.不幸的是,下面的代码将日期返回到UTC时区.请注意,当您运行以下代码时,纽约时间午夜之前的日期如何更改为其午夜后UTC时间日期.

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 默认为UTC,因此您可以手动指定时区以使其正常工作.另外,您可以使用 lubridate 中的 date()提取器,这种提取器更适合时区.

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"

reprex程序包(v0.2.0)创建于2018-09-25.

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

这篇关于更改R中的时区,但不返回原始时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆