Search code examples
pythondatetimedatefinder

Convert string to date using datefinder


An issue occurs when I try to find a date in a .txt file using datefinder. I have the feeling I am unnecessarily switching between data types to obtain the result I desire.

Underneath is a MWE which results in generator object, which in turn is empty when changed to a list. I would like to obtain a datetime in the format %d-%m-%Y. MWE:

import datefinder 

f = ['this is text', 'this is a date', '* Model creation date:            Sun Apr 25 08:52:06 2021']
for line in f:
    if "creation date" in line: 
        date_line = str(line)
        rev_date = datefinder.find_dates(_date_line)

Solution

  • dateutil's parser seems to do a better job:

    import dateutil
    
    f = ['this is text', 'this is a date', '* Model creation date:            Sun Apr 25 08:52:06 2021']
    dates = []
    
    for line in f:
        try:
            dates.append(dateutil.parser.parse(line, fuzzy=True))
        except dateutil.parser.ParserError:
            pass
        
    print(dates)    
    # [datetime.datetime(2021, 4, 25, 8, 52, 6)]
    

    For the specific use-case:

    for line in f:
        if "* Model creation date:" in line:
            rev_date = dateutil.parser.parse(line, fuzzy=True)
            break
    print(rev_date)    
    # 2021-04-25 08:52:06