【发布时间】:2013-10-01 22:30:22
【问题描述】:
我有一个日期字符表示向量,其中格式主要是 dmY(例如 27-09-2013)、dmy(例如 27-09-13),偶尔还有一些 b 或 @987654327 @月。因此,parse_date_time 包 lubridate 中的“允许用户指定几种格式顺序来处理异构日期时间字符表示”对我来说可能是一个非常有用的功能。
但是,parse_date_time 似乎在解析 dmy 日期与 dmY 日期一起出现时出现问题。单独解析 dmy 或 dmy 以及与我相关的其他一些格式时,它工作正常。在对@Peyton 的回答here 的评论中也注意到了这种模式。有人建议快速修复,但我想问一下是否可以在lubridate 中处理它。
这里我展示了一些示例,其中我尝试解析 dmy 格式的日期以及其他一些格式,并相应地指定 orders。
library(lubridate)
# version: lubridate_1.3.0
# regarding how date format is specified in 'orders':
# examples in ?parse_date_time
# parse_date_time(x, "ymd")
# parse_date_time(x, "%y%m%d")
# parse_date_time(x, "%y %m %d")
# these order strings are equivalent and parses the same way
# "Formatting orders might include arbitrary separators. These are discarded"
# dmy date only
parse_date_time(x = "27-09-13", orders = "d m y")
# [1] "2013-09-27 UTC"
# OK
# dmy & dBY
parse_date_time(c("27-09-13", "27 September 2013"), orders = c("d m y", "d B Y"))
# [1] "2013-09-27 UTC" "2013-09-27 UTC"
# OK
# dmy & dbY
parse_date_time(c("27-09-13", "27 Sep 2013"), orders = c("d m y", "d b Y"))
# [1] "2013-09-27 UTC" "2013-09-27 UTC"
# OK
# dmy & dmY
parse_date_time(c("27-09-13", "27-09-2013"), orders = c("d m y", "d m Y"))
# [1] "0013-09-27 UTC" "2013-09-27 UTC"
# not OK
# does order of the date components matter?
parse_date_time(c("2013-09-27", "13-09-13"), orders = c("Y m d", "y m d"))
# [1] "2013-09-27 UTC" "0013-09-27 UTC"
# no
select_formats 参数呢?很抱歉这么说,但我很难理解帮助文件的这一部分。还有一个search for select_formats on SO: 0 个结果。不过,这部分似乎是相关的:“默认情况下,选择具有最多格式化令牌 (%) 的格式,并且 %Y 计为 2.5 个令牌(因此它可以优先于 %y%m)。”。所以我(拼命地)尝试了一些额外的dmy日期:
parse_date_time(c("27-09-2013", rep("27-09-13", 10)), orders = c("d m y", "d m Y"))
# not OK. Tried also 100 dmy dates.
# does order in the vector matter?
parse_date_time(c(rep("27-09-13", 10), "27-09-2013"), orders = c("d m y", "d m Y"))
# no
然后我检查了guess_formats 函数(也在lubridate 中)如何处理dmy 和dmY:
guess_formats(c("27-09-13", "27-09-2013"), c("dmy", "dmY"), print_matches = TRUE)
# dmy dmY
# [1,] "27-09-13" "%d-%m-%y" ""
# [2,] "27-09-2013" "%d-%m-%Y" "%d-%m-%Y"
# OK
来自?guess_formats:y also matches Y。来自?parse_date_time:y* Year without century (00–99 or 0–99). Also matches year with century (Y format)。所以我尝试了:
guess_formats(c("27-09-13", "27-09-2013"), c("dmy"), print_matches = TRUE)
# dmy
# [1,] "27-09-13" "%d-%m-%y"
# [2,] "27-09-2013" "%d-%m-%Y"
# OK
因此,guess_format 似乎能够与dmY 一起处理dmy。但是我怎么能告诉parse_date_time 做同样的事情呢?提前感谢任何 cmets 或帮助。
更新
我在lubridate bug report 上发布了这个问题,并得到了@vitoshka 的快速回复:“这是一个错误”。
【问题讨论】: