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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Here, I suppose that you want to parse dates in different formats (and perhaps even languages). If you just need the datestring out of some text, use dateutil like the other commenters recommend...
I had this task some time ago as well, and I used pyParsing for creating a parser based on my requirements, although any decent parser should do. It is far easier to read, test and to debug than regular expressions.
I do have some (although crappy) example code on my blog that aims to find date expressions in USA format and German format alike. It may not be what you need, but it's pretty well adjustable.
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.
I found the following very useful for converting the time to a uniform format and then searching for this format pattern:
from datetime import datetime
date_object = datetime.strptime('March-1-05', '%B-%d-%y')
print date_object.strftime("%B %d, %Y")
Also you can try dateutil.parser... Did not tried it myself, but heard some good comments. python-dateutil
As far as I can tell, there is no such module in standard python library. There are so many different date formats that it's hard to catch them all. If I was you, I will turn to Regex. refer to this page