Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module to extract probable dates from strings?

Tags:

python

I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like Date::Extract in Perl

Thank you in advance.

like image 233
Daniel Gasull Avatar asked Nov 12 '08 21:11

Daniel Gasull


People also ask

How do I extract date and time from text in Python?

Extracting Dates from a Text File with the Datefinder Module. The Python datefinder module can locate dates in a body of text. Using the find_dates() method, it's possible to search text data for many different types of dates. Datefinder will return any dates it finds in the form of a datetime object.

How do I grab a date in Python?

today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

What is parse dates in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.

How do I extract a specific part of a string in Python?

You can extract a substring from a string before a specific character using the rpartition() method. rpartition() method partitions the given string based on the last occurrence of the delimiter and it generates tuples that contain three elements where.


2 Answers

The nearest equivalent is probably the dateutil module. Usage is:

>>> from dateutil.parser import parse
>>> parse("Wed, Nov 12")
datetime.datetime(2008, 11, 12, 0, 0)

Using the fuzzy parameter should ignore extraneous text. ie

>>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True)
datetime.datetime(2006, 12, 1, 14, 30)
like image 119
Brian Avatar answered Oct 24 '22 12:10

Brian


Why no give parsedatetime a try?

like image 36
Ber Avatar answered Oct 24 '22 10:10

Ber