我编写了代码来从给定字符串中提取日期。给定
> "Date: 2012-07-29, 12:59AM PDT"
它提取
> "2012-07-29"
问题是我的代码看起来又长又难读。我想知道是否有一种更优雅的方式来做到这一点。
raw_date = "Date: 2012-07-29, 12:59AM PDT"
#extract the string from raw date
index = regexpr("[0-9]{4}-[0-9]{2}-[0-9]{2}", raw_date) #returns 'start' and 'end' to be used in substring
start = index #start represents the character position 's'. start+1 represents '='
end = attr(index, "match.length")+start-1
date = substr(raw_date,start,end); date
您可以使用strptime()
解析时间对象:
R> strptime("Date: 2012-07-29, 11:59AM PDT", "Date: %Y-%m-%d, %I:%M%p", tz="PDT")
[1] "2012-07-29 11:59:00 PDT"
R>
请注意,我移动了您的输入字符串,因为我不确定 12:59AM 是否存在...只是为了证明这一点,移动了三个小时(以秒表示,基本单位):
R> strptime("Date: 2012-07-29, 11:59AM PDT",
+> "Date: %Y-%m-%d, %I:%M%p", tz="PDT") + 60*60*3
[1] "2012-07-29 14:59:00 PDT"
R>
哦,如果你只想要日期,那当然更简单:
R> as.Date(strptime("Date: 2012-07-29, 11:59AM PDT", "Date: %Y-%m-%d"))
[1] "2012-07-29"
R>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)