用格式转换其他字符的日期 [英] Converting date with additional characters in format

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

问题描述

我有一个要解析为日期 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"?

推荐答案

您无需删除转换中未使用的字符规范。在?strptime 的详细信息部分中,我们发现:

You don't need to strip the characters not used in the conversion specification. In the Details section of ?strptime we find that:


[a]格式字符串中的ny字符不是转换规范的一部分,将按字面解释

"[a]ny character in the format string not part of a conversion specification is interpreted literally"

即,在中格式 as.Date 的格式,您不仅可以包含转换说明(由)以及其他字符:

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


根据指定格式对字符字符串进行必要的处理:忽略任何尾随字符

Character strings are processed as far as necessary for the format specified: any trailing characters are ignored

因此,这可行:

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

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

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