lubridate的怪异行为:在特定日期加上特定天数会产生NA

问题描述 投票:2回答:1

我正在使用lubridate在日期上执行多项操作,并且在某些时候,我需要在要使用的日期前加上6天。我在循环中执行此操作,它几乎适用于每个日期,但是在此特定日期上,总和返回NA

library(lubridate)
testDate <- ymd("2018-10-29", tz = "America/Sao_Paulo")

testDate + days(4) #OK
testDate + days(5) #OK
testDate + days(6) #Returns NA
testDate + days(7) #OK
testDate + days(8) #OK
testDate + days(9) #OK

有人可以帮助我了解为什么会这样吗?

会话信息:

R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] lubridate_1.7.4

loaded via a namespace (and not attached):
[1] compiler_3.6.0 magrittr_1.5   tools_3.6.0    Rcpp_1.0.3     stringi_1.4.3  stringr_1.4.0 
r lubridate
1个回答
3
投票

如@akrun所建议,这是夏令时的问题。查看6之前和之后的日子:

format(testDate + days(c(5,7)), format = "%Y-%m-%d %H:%M:%S")
# [1] "2018-11-03 00:00:00" "2018-11-05 00:00:00"

您会注意到它假设为“午夜”(正如人们可能期望的那样。

[2018年在巴西圣保罗,午夜4点(ref)午夜向前滚动:

当当地标准时间即将达到 2018年11月4日,星期日,[[[12:00:00午夜]的时钟已前进 1小时 2018年11月4日,星期日,1:00:00 am改为夏令时。

这意味着存在11月3日23:59:59,但是只要它向前转一秒,就变成11月4日,01:00:00。这表明(从数学上)11月3日00:00:00根本不存在。

因此,R通过返回NA来告诉您

timestamp不是合法时间。>>但是,您可以很轻松地处理Date对象:

testDate + days(5:7) # [1] "2018-11-03 -03" NA "2018-11-05 -02" as.Date(testDate) + days(5:7) # [1] "2018-11-03" "2018-11-04" "2018-11-05"

© www.soinside.com 2019 - 2024. All rights reserved.