本文介绍了解析带有其他字符的字符串,格式为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要解析为类 Date 的字符串变量.除了日,年和月之外,该格式还具有其他字符,例如分隔符(),字母和撇号( u''),如下所示:

I have a string variable that I want to parse to class Date. In addition to the day, year and month, the format has other characters like separators (, ), letters and apostrophes (u''), like this:

'u'9',u'2005',u'06''

我尝试过

as.Date(my_data$date, format = '%d %Y %m')

...但是它只会产生缺失的值.我希望R将 u''解释为一个unicode指示符,而事实并非如此.

...but it only produces missing values. I was hoping that R would interpret the u'' as a unicode designator, which it doesn't.

我如何剥离所有那些未使用的字符,以使此"u'9',u'2005',u'06'" 变成该"9 2005 06"; ?

How do I strip all those unused characters so that this "u'9', u'2005', u'06'" becomes simply this "9 2005 06"?

推荐答案

您无需删除转换规范中未使用的字符.在?as.Date 中, format 参数指向?strptime (否则,通过 strptime ").在?strptime *的详细信息"部分中,我们发现:

You don't need to strip the characters not used in the conversion specification. In ?as.Date, the format argument is pointing to ?strptime ("Otherwise, the processing is via strptime"). In the Details section of ?strptime* we find that:

也就是说,在 as.Date format 参数中,您不仅可以包括转换规范(由引入),还可以包括还有其他字符":

That is, in the format argument of as.Date, you may include not only the conversion specification (introduced by %) but also the "other characters":

此外,来自?as.Date :

因此,这可行:

as.Date("(u'9', u'2005', u'06')", format = "(u'%d', u'%Y', u'%m")
# [1] "2005-06-09"

这篇关于解析带有其他字符的字符串,格式为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:00