是否有更短的方法从字符串中提取日期?

时间:2012-08-01 21:57:58

标签: r

我编写了代码来从给定字符串中提取日期。鉴于

  > "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

4 个答案:

答案 0 :(得分:13)

您可以使用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:59存在...只是为了证明这一点,移动了三个小时(以秒为单位表示基本单位):

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> 

答案 1 :(得分:5)

有些事情应该有效:

x <- "Date: 2012-07-29, 12:59AM PDT"
as.Date(substr(x, 7, 16), format="%Y-%m-%d")

答案 2 :(得分:4)

就像(几乎)一样,你在这里有多种选择。虽然它们都没有真正让你习惯于一些基本的正则表达式语法(或其亲密朋友)。

raw_date <- "Date: 2012-07-29, 12:59AM PDT"

备选方案1

> gsub(",", "", unlist(strsplit(raw_date, split=" "))[2])
[1] "2012-07-29"

备选方案2

> temp <- gsub(".*: (?=\\d?)", "", raw_date, perl=TRUE)
> out <- gsub("(?<=\\d),.*", "", temp, perl=TRUE)
> out
[1] "2012-07-29"

备选方案3

> require("stringr")
> str_extract(raw_date, "\\d{4}-\\d{2}-\\d{2}")
[1] "2012-07-29"

答案 3 :(得分:2)

带反向引用的正则表达式:

> sub("^.+([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]).+$","\\1","Date: 2012-07-29, 12:59AM PDT")
[1] "2012-07-29"

但是@Dirk是正确的,将它解析为日期是正确的方法。