103

The function to get a datetime from a string, datetime.strptime(date_string, format) requires a string format as the second argument. Is there a way to build a datetime from a string without without knowing the exact format, and having Python best-guess it?

Yarin
  • 173,523
  • 149
  • 402
  • 512
  • 2
    possible duplicate of [Is there any python library for parsing dates and times from a natural language?](http://stackoverflow.com/questions/1495487/is-there-any-python-library-for-parsing-dates-and-times-from-a-natural-language) – Andrew Walker Feb 29 '12 at 22:32
  • 5
    Differentiating between mm/dd/yyyy vs. dd/mm/yyyy is an interesting problem, with disastrous results if you get it wrong. – Mark Ransom Feb 29 '12 at 22:46
  • 1
    It depends how inexact you mean to be when you say, "without the exact format." Could you give examples of the types of inputs you want to be able to handle? Or, could you potentially have partial info about the format (such as whether the year is 2 or 4 digits, or whether the month precedes the day or vice versa)? Without at least some basic info, even a person can't do what you ask. Is 01/02/12 Feb 1st 2012, Jan 2nd 2012, Feb 12th 2001, Dec 2nd 2001, or something else? – Silas Ray Feb 29 '12 at 23:46
  • 1
    https://github.com/jeffreystarr/dateinfer – denfromufa Jul 26 '17 at 17:54
  • @denfromufa I get the following error while importing dateinfer on Python3: from infer import infer ModuleNotFoundError: No module named 'infer' – TanviP Jun 21 '18 at 06:47

4 Answers4

160

Use the dateutil library.

I was already using dateutil as an indispensable lib for handling timezones
(See Convert UTC datetime string to local datetime and How do I convert local time to UTC in Python?)

And I've just realized it has date parsing support:

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)

(See also How do I translate a ISO 8601 datetime string into a Python datetime object?)

Community
  • 1
  • 1
Yarin
  • 173,523
  • 149
  • 402
  • 512
31

Can get away with a simple function if only checking against dates.

def get_date(s_date):
    date_patterns = ["%d-%m-%Y", "%Y-%m-%d"]

    for pattern in date_patterns:
        try:
            return datetime.datetime.strptime(s_date, pattern).date()
        except:
            pass

    print "Date is not in expected format: %s" %(s_date)
    sys.exit(0)
Sandeep
  • 28,307
  • 3
  • 32
  • 24
9

Back before I was a python guy, I was a perl guy. One of the things that I've always missed but haven't seen anything close to it is Date::Manip. That module can extract a good timestamp from a smattering of nibbles. I almost suspect that it's author struck a deal with the Devil.

I've run across a few things that take stabs at it in Python:

If you find anything better I'd love to hear about it though.

synthesizerpatel
  • 27,321
  • 5
  • 74
  • 91
  • 1
    Thanks for the recommendations- See my answer though, think I found my own answer with the [dateutil](http://pypi.python.org/pypi/python-dateutil/1.5) library. – Yarin Mar 01 '12 at 13:46
8

You can use datefinder ,It will detect all types of natural style of dates.

import datefinder # Module used to find different style of date with time

string_value = " created 01/15/2005 by ACME inc.and associates.January 4th,2017 at 8pm"
matches = datefinder.find_dates(string_value)            
for match in matches:
    print("match found ",match)

Output

match found  2005-01-15 00:00:00
match found  2017-01-04 20:00:00
Copperfield
  • 8,131
  • 3
  • 23
  • 29
  • Unlike dateutil, datefinder can't parse a bare month, eg. "July" (without either a day or a year.) This is kind of a major limitation that would seem to be a trivial fix. – Forest May 29 '20 at 00:41
  • Cant find the date in `02-08-2021 - 10_789_0107987_1_165` – West Jun 09 '22 at 06:14