Search code examples
pythondatedatefinder

python datefinder.find_dates does not work if only years are present e.g '2014 - 2018'


I am trying to extract dates from a string if only years are present, e.g the following string:

'2014 - 2018'

should return the following dates:

2014/01/01
2018/01/01

I am using the python library datefinder and it's brilliant when other element like a month is specified but fails when only years are present in a date.

I need to recognise all sort of incomplete and complete dates:

2014
May 2014
08/2014
03/10/2018
01 March 2013

Any idea how to recognise date in a string when only the year is present?

Thank you


Solution

  • you can use regex expression to find year.

    Example :

    import re
    
    
    def print_year_from_text(text):
        matches=re.search(r"\b\d{4}\b",text)
        year=None
        if matches :
            year=matches.group()
        
        print("Text = " + text)
        print(f"Year = {year}")
        print("")
        
    
    print_year_from_text("Cette phrase contient l'année 2023.")
    print_year_from_text("Cette phrase ne contient pas d'année.")