【发布时间】:2025-11-29 16:55:02
【问题描述】:
我今天在尝试从日期时间列创建日期列并且无法保留正确的时区时遇到了一个有趣的问题。问题是,在下面的示例中,为什么似乎无法修改“日期”列的时区?
这是一个可重现的例子:
library(lubridate)
# create a short datetime sequence
df <- data.frame(datetime = seq(ymd_hm("2020-1-1 0:00"), ymd_hm("2020-1-3 12:00"), by = "hour"))
# check the timezone -- it is UTC
tz(df$datetime)
# convert to PST
df$datetime <- force_tz(df$datetime, "US/Pacific")
# confirm -- OK
tz(df$datetime) # [1] "US/Pacific"
# now create a date column based on the datetime column
df$date <- as.Date(df$datetime)
# might think it would be PST, but it's UTC
tz(df$date)
# attempt to change it manually to PST
df$date <- force_tz(df$date, tz="US/Pacific")
# doesn't work
tz(df$date) # [1] "UTC"
# seems we're stuck -- the date column reflects UTC and changes to January 2nd at 4PM on 1/1
# in the datetime column
df[15:20,]
输出在技术上是正确的(即 8 小时偏移量),但在两列中有两个不同的时区似乎非常令人困惑。
datetime date
15 2020-01-01 14:00:00 2020-01-01
16 2020-01-01 15:00:00 2020-01-01
17 2020-01-01 16:00:00 2020-01-02
18 2020-01-01 17:00:00 2020-01-02
19 2020-01-01 18:00:00 2020-01-02
20 2020-01-01 19:00:00 2020-01-02
【问题讨论】:
-
可能检查您的 R/lubridate 版本,因为
force_tz对我有用(lubridate 1.7.9,R 4.0.2)。 -
感谢@heds1,对 1.7.9 的更新似乎确实修复了“日期”列的标称时区,但随后输出与上面示例中的输出相同,其中日期仍然提前到 1 月 2 日下午 4 点在日期时间列中。这也是你得到的吗?
标签: r datetime timezone lubridate