Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Is there a way to robustly extract date and time from a text? Say for example:

...The event will be held on 17/10/2013 at 3:30 PM in the room 121 and everyone is welcome...

should return:

{2013, 10, 17, 15, 30, 0}

The emphasis here is on robustness of the extraction. The same output is expected when the date is slightly twisted as follows:

...The event will be held on 17th October 2013 at 3:30 PM in the room 121 and ...

...The event will be held on October 17th 2013 at 3:30 PM in the room 121 and ...

...The event will be held on 17 October 2013 at 3:30 PM in the room 121 and ...

I guess this is a fairly trivial problem in natural language processing, though I am not aware of the state-of-the-art. I think simple regular expressions are the way to go. Is there an existing resource that can do this?

share|improve this question
    
PHP has a very neat function, strtotime, that will interpret strings. It is very robust because it has a large list of different patterns that it matches. These patterns are available here: se1.php.net/manual/en/datetime.formats.php –  Pickett Oct 9 '13 at 7:05
    
Nice find! Thanks –  my account_ram Oct 9 '13 at 13:42

1 Answer 1

string="The event will be held on 7/10/2013 at 3:30 PM in the room 121 and \
everyone is welcome";

extract the date and time:

dateTime=StringCases[string, ___ ~~ 
   x : DatePattern[{"Month", "/", "Day", "/", "Year", " at ", "Hour", 
      ":", "Minute", " ", "AMPM"}] ~~ ___ :> x]

(*  {"7/10/2013 at 3:30 PM"}  *)

Make into a date list

DateList[{First@dateTime, {"Month", "/", "Day", "/", "Year", " at ", 
   "Hour", ":", "Minute", " ", "AMPM"}}]

(*  {2013, 7, 10, 15, 30, 0.}  *)

You can do the same for the other examples by changing the date pattern.

Edit

or just create your date pattern list:

pattern = {"Month", "/", "Day", "/", "Year", " at ", "Hour", ":", 
  "Minute", " ", "AMPM"}

then:

dateTime = StringCases[string, ___ ~~ x : DatePattern[pattern] ~~ ___ :> x];
DateList[{First@dateTime, pattern}]

(*  {2013, 7, 10, 15, 30, 0.}  *)
share|improve this answer
    
Just a minor point...the datetime format is non US in example so pattern={"Day", "/", "Month", "/", "Year", " at ", "Hour", ":", "Minute", " \ ", "AMPM"} will extract the correct October not July date. Also, DateList[{StringCases[string, DatePattern[pattern]][[1]], pattern}]` works –  ubpdqn Oct 9 '13 at 11:41
    
@ubpdqn thanks. I'll fix. –  Mike Honeychurch Oct 9 '13 at 22:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.