不能识别%b /%B? [英] strptime not recognizing %b/%B?

查看:109
本文介绍了不能识别%b /%B?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用strptime转换R中的某些日期。我已阅读此主题并设置我的区域设置,以便它应该工作。例如:

I'm trying to convert some dates in R with strptime. I've read this thread and have set my locale so that it should work. For example:

> Sys.getlocale("LC_TIME")
[1] "en_GB"
> format(Sys.time(), format="%B")
[1] "November"

但是,如果我尝试转换一个月的字符串,strptime返回NA,例如:

However if I try to convert a month string, strptime returns NA, e.g.:

> strptime("November", format="%B")
[1] NA

我可以在上面的链接中运行示例,但是如果我简化了这个例子,只需要包含这个月份,那么我再次获得NA。

I can run the example at the above link without any problem but if I simplify the example to just include the month, I get NA again.

> var <- "Thu Nov 8 15:41:45 2012"
> strptime(var, format="%a %b %d %H:%M:%S %Y")
[1] "2012-11-08 15:41:45 GMT"
> strptime("Nov", format="%b")
[1] NA

这里发生了什么?如何将字符月份解析为日期对象?

What's going on here? How can I parse a character month into a date object?

编辑
感谢您的评论。为了澄清,这也不起作用:

EDIT Thanks for the comments below. To clarify, this also doesn't work:

> strptime("November 2011", format="%B %Y")
[1] NA

我也会期待 strptime 填写当前系统时间的任何缺失的字段,如 strptime(2011,format = %Y)

I would also expect strptime to fill in any missing fields with the current system time, as in strptime("2011", format="%Y")

推荐答案

我有点困惑于R的行为,在缺少值的情况下在 strptime 中。文档清楚:

I am a bit confused by R's behaviour in the case of missing values in strptime. The documentation is clear enough:


对于strptime,输入字符串不需要完全指定日期:
假定未指定秒分钟或小时为零,而
未指定的年,月或日是当前的。某些组件可能会以$($ t
空字符串形式表示)中的
返回。

For strptime the input string need not specify the date completely: it is assumed that unspecified seconds, minutes or hours are zero, and an unspecified year, month or day is the current one. Some components may be returned as NA (but an unknown tzone component is represented by an empty string).

但是,这几个月并不总是如此。这是一个特别奇怪的例子:

But that doesn't always seem to be the case with months. Here is a particularly odd example:

strptime('Nov-01', '%B-%d')
[1] "2014-11-01"
strptime('2009-Nov', '%Y-%B')
[1] NA

基于上述的一个明显的解决方法是使一个简单的功能。

An obvious workaround based on the above would be to make a simple function.

convert.months <- function(x) 
     strptime(paste(x,strftime(Sys.time(),'%d')), '%b %d')

哪个是丑陋的,但它有效:

Which is ugly, but it works:

convert.months(c("Nov","Dec"))
[1] "2014-11-18 EST" "2014-12-18 EST"






要清楚这里是测试用例,根据对于我对文档的解释,应该都可以正常工作:


To be clear here are the test cases, which, according to my interpretation of the documentation, should all work:

strptime('11', '%m') # Fail
strptime('11-01', '%m-%d') # Works
strptime('2009-11', '%Y-%m') # Fail

strptime('Nov', '%b') # Fail
strptime('Nov-01', '%b-%d') # Works
strptime('2009-Nov', '%Y-%b') # Fail

这篇关于不能识别%b /%B?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆