【发布时间】:2017-01-24 09:21:36
【问题描述】:
我有以下问题:我得到的数据中的日期列包含由于夏令时不存在的日期。 (例如 2015-03-29 02:00 在欧洲中部时间不存在,因为 DST 在这一天生效,时钟直接从 01:59 设置到 03:00)
是否有一种简单可靠的方法来确定日期是否对夏令时有效?
由于日期时间类的属性,这不是微不足道的。
# generating the invalid time as POSIXlt object
test <- strptime("2015-03-29 02:00", format="%Y-%m-%d %H:%M", tz="CET")
# the object seems to represent something at least partially reasonable, notice the missing timezone specification though
test
# [1] "2015-03-29 02:00:00"
# strangely enough this object is regarded as NA by is.na
is.na(test)
# [1] TRUE
# which is no surprise if you consider:
is.na.POSIXlt
# function (x)
# is.na(as.POSIXct(x))
as.POSIXct(test)
# [1] NA
# inspecting the interior of my POSIXlt object:
unlist(test)
# sec min hour mday mon year wday yday isdst zone gmtoff
# "0" "0" "2" "29" "2" "115" "0" "87" "-1" "" NA
所以我想到的最简单的方法是检查POSIXlt对象的isdst字段,POSIXt的帮助描述该字段如下:
isdst
夏令时标志。有效时为正,否则为零, 如果未知,则为负。
是否检查isdst 字段是否保存,因为如果日期由于 dst 更改而无效,则此字段仅是 -1,或者由于某些其他原因它可以是 -1?
关于版本、平台和语言环境的信息
R.version
# _
# platform x86_64-w64-mingw32
# arch x86_64
# os mingw32
# system x86_64, mingw32
# status
# major 3
# minor 3.1
# year 2016
# month 06
# day 21
# svn rev 70800
# language R
# version.string R version 3.3.1 (2016-06-21)
# nickname Bug in Your Hair
Sys.getlocale()
# [1] "LC_COLLATE=German_Austria.1252;LC_CTYPE=German_Austria.1252;LC_MONETARY=German_Austria.1252;LC_NUMERIC=C;LC_TIME=English_United States.1252"
【问题讨论】:
-
我无法重现您的示例。当我执行您的代码时,我没有得到
is.na(test) FALSE,而是TRUE,并且在执行test时我得到了时区CEST。两种可能:(1) Sys.getlocale(),(2) 你用的是什么 R 版本? -
is.na(test)应该是TRUE我正在使用Sys.getlocale("LC_TIME")"German_Austria.1252"但如果我使用Sys.setlocale("LC_TIME", "german")以及Sys.setlocale("LC_TIME", "english")strptime 中的时区设置,示例结果相同应该注意选择正确的时区。 R版本是:R版本3.3.1(2016-06-21)运行在:x86_64-w64-mingw32(64位Windows 7) -
猜猜它取决于操作系统,我也无法重现您的示例。如果您尝试
as.POSIXct(test)会发生什么?我在 Linux 上,我注意到POSIXlt对象有时代表无效时间,而POSIXct不代表。如果我尝试as.POSIXct(test)我得到2015-03-29 01:00:00 CET,即日期时间已更正。也许您可以尝试identical(as.POSIXlt(as.POSIXct(test)),test)获得您的支票。 -
对不起我的第一篇文章。我有
is.na(test) FALSE,而不是你的例子中的TRUE。顺便说一句:有一个名为anytime的新包,它可以转换“任何”时间格式。你可以试试这个(下载后),对我来说它有效:anytime::anytime(test)[1] "2015-03-29 01:00:00 CET" -
例如
NaNs 也可以有不同的位表示,NaN的帮助文件说不要在它们上使用identical。