Is there a shorter way to extract a date from a string?

前端 未结 4 2143
轮回少年
轮回少年 2021-01-12 02:14

I wrote code to extract the date from a given string. Given

  > \"Date: 2012-07-29, 12:59AM PDT\"

it extracts

  > \"         


        
4条回答
  •  余生分开走
    2021-01-12 03:09

    You can use strptime() to parse time objects:

    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> 
    

    Note that I shifted your input string as I am unsure that 12:59AM exists... Just to prove the point, shifted by three hours (expressed in seconds, the base units):

    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> 
    

    Oh, and if you just want the date, it is of course even simpler:

    R> as.Date(strptime("Date: 2012-07-29, 11:59AM PDT", "Date: %Y-%m-%d"))
    [1] "2012-07-29"
    R> 
    

提交回复
热议问题