I want to be able to read a string and return the first date appears in it. Is there a ready module that I can use? I tried to write regexs for all possible date format, but it is quite long. Is there a better way to do it?
Python – finding date in a string
datepythonstring
Related Topic
- Python – What are metaclasses in Python
- Python – Does Python have a ternary conditional operator
- Javascript – find documentation on formatting a date in JavaScript
- Javascript – How to replace all occurrences of a string in JavaScript
- Javascript – Detecting an “invalid date” Date instance in JavaScript
- Javascript – How to check whether a string contains a substring in JavaScript
- Python – Does Python have a string ‘contains’ substring method
- Python – How to iterate over rows in a DataFrame in Pandas
Best Answer
You can run a date parser on all subtexts of your text and pick the first date. Of course, such solution would either catch things that are not dates or would not catch things that are, or most likely both.
Let me provide an example that uses
dateutil.parser
to catch anything that looks like a date:The result from the code is, quite unsurprisingly, rubbish whether you allow overlapping or not. If overlapping is allowed, you get a lot of dates that are nowhere to be seen, and if if it is not allowed, you miss the important date in the text.
Essentially, if overlapping is allowed:
If, however, overlapping is not allowed, "2009. On 1st July 2058" is parsed as 2009-07-01 20:58:00 and no attempt is made to parse the date after the period.