升级R 4.4与lubridate 1.9.3后添加时间间隔出现无效时区错误
解决lubridate 1.9.3 + R 4.4.0中POSIXct添加时间间隔的时区错误
最近升级到R 4.4.0和lubridate 1.9.3后,尝试给POSIXct变量添加时间间隔时触发以下错误:
Error in C_time_add(time, periods, roll_month, roll_dst) : CCTZ: Invalid timezone of the input vector: ""
谷歌搜索发现这个问题曾在lubridate旧版本中出现但已修复,短时间间隔可以通过计算秒数添加,但月份或年份这类间隔无法用此方法,求可行解决建议。
错误复现
执行以下代码时触发错误:
as.POSIXct("2024-5-23") + days(1)
返回错误信息:
Error in C_time_add(time, periods, roll_month, roll_dst) : CCTZ: Invalid timezone of the input vector: ""
正常对比(as.Date可用)
使用as.Date处理时可以正常执行:
as.Date("2024-5-23") + days(1) # [1] "2024-05-24"
环境信息
> sessionInfo() R version 4.4.0 (2024-04-24 ucrt) Platform: x86_64-w64-mingw32/x64 Running under: Windows 10 x64 (build 19045) Matrix products: default locale: [1] LC_COLLATE=English_United States.utf8 LC_CTYPE=English_United States.utf8 LC_MONETARY=English_United States.utf8 LC_NUMERIC=C LC_TIME=English_United States.utf8 time zone: America/New_York tzcode source: internal attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] lubridate_1.9.3 loaded via a namespace (and not attached): [1] vctrs_0.6.5 generics_0.1.3 tools_4.4.0 compiler_4.4.0 cli_3.6.2 timechange_0.3.0 rlang_1.1.3 glue_1.7.0 rstudioapi_0.16.0
解决方法
- 显式指定时区:创建POSIXct对象时,通过
tz参数明确指定时区,可匹配系统当前时区或使用默认值:# 指定系统当前时区 as.POSIXct("2024-5-23", tz = "America/New_York") + days(1) # 使用系统默认时区 as.POSIXct("2024-5-23", tz = "") + days(1) - 使用lubridate解析函数:用lubridate自带的
ymd/mdy等函数替代base R的as.POSIXct,这些函数会自动处理时区:# 指定时区 ymd("2024-5-23", tz = "America/New_York") + days(1) # 使用系统默认时区 ymd("2024-5-23") + days(1) - 更新依赖包:lubridate依赖timechange包,尝试更新到最新版本修复潜在兼容问题:
install.packages("timechange")
内容的提问来源于stack exchange,提问作者user25209989
相关产品推荐
相关产品推荐

