2
library("anytime")

这很好用:

anytime("08/24/2014 01:28:00")
anytime("2014/08/24 01:28:00")

[1] "2014-08-24 00:28:00 NZST"

这不会:

anytime("24/08/2014 01:28:00")
anytime("2014/24/08 01:28:00")

[1] NA

这是什么原因以及选项是什么(仅使用任何时间包)?

4

1 回答 1

3

如果格式不在默认格式列表中,我们可以使用addFormatsin添加格式anytime

getFormats()
#[1] "%Y-%m-%d %H:%M:%S%f"    "%Y/%m/%d %H:%M:%S%f"    "%Y%m%d %H%M%S%f"       
#[4] "%Y%m%d %H:%M:%S%f"      "%m/%d/%Y %H:%M:%S%f"    "%m-%d-%Y %H:%M:%S%f"   
#[7] "%Y-%b-%d %H:%M:%S%f"    "%Y/%b/%d %H:%M:%S%f"    "%Y%b%d %H%M%S%F"       
#[10] "%Y%b%d %H:%M:%S%F"      "%b/%d/%Y %H:%M:%S%f"    "%b-%d-%Y %H:%M:%S%f"   
#[13] "%d.%b.%Y %H:%M:%S%f"    "%Y-%B-%d %H:%M:%S%f"    "%Y/%B/%d %H:%M:%S%f"   
#[16] "%Y%B%d %H%M%S%f"        "%Y%B%d %H:%M:%S%f"      "%B/%d/%Y %H:%M:%S%f"   
#[19] "%B-%d-%Y %H:%M:%S%f"    "%d.%B.%Y %H:%M:%S%f"    "%a %b %d %H:%M:%S%F %Y"
#[22] "%Y-%m-%d"               "%Y%m%d"                 "%m/%d/%Y"              
#[25] "%m-%d-%Y"               "%Y-%b-%d"               "%Y%b%d"                
#[28] "%b/%d/%Y"               "%b-%d-%Y"               "%Y-%B-%d"              
#[31] "%Y%B%d"                 "%B/%d/%Y"               "%B-%d-%Y"   

如果我们检查format给出 NA 的,它不在getFormats列表中

c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S") %in% getFormats()
#[1] FALSE FALSE

因此,我们可以添加格式addFormats并应用anytime

anytime::addFormats(c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S")) 
anytime("24/08/2014 01:28:00")
#[1] "2014-08-24 01:28:00 IST"
anytime("2014/24/08 01:28:00")
#[1] "2014-08-24 01:28:00 IST"

更新

在最新版本中anytime,共有 41 种格式getFormats()

length(getFormats())
#[1] 41

但是,OP 帖子中指定的格式仍然不包括在内,必须遵循addFormats路线

于 2017-04-02T07:58:39.873 回答