[Python] Parsing dates from strings that contain unrelated text while avoiding parsing...

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    What I want to Achieve
    My goal is to extract a date that has at least a day and a Month, but could also have a minute, hour, and year.

    I want to avoid the parser finding integers and thinking that implies a day of the current month.

    Furthermore, I also want the parser to find a date that is only a small part of a larger string.

    Think:

    'Today is the most wonderful 27th of March 2025' = datetime.datetime(2025, 3, 27, 0, 0)
    '2gb of ram' != datetime.datetime(2025, 3, 2, 0, 0) (Assuming we are currently in March)

    What I tried so far

    Using the fuzzy=True argument in dateutils

    from dateutil import parser

    #OK: Correct Datetime is returned: datetime.datetime(2025, 3, 30, 0, 0)
    parser.parse('Today is the most wonderful 30th March 2025', fuzzy=True)

    #NOT OK: Integer is not ignored, Datetime is returned: datetime.datetime(2025, 3, 2, 0, 0)
    parser.parse('2 is my lucky number', fuzzy=True)


    Using the REQUIRED_PARTS setting in dateparser

    frome dateparser import parse

    # OK: Returns correct datetime: datetime.datetime(2025, 3, 30, 0, 0
    parse('30 March', settings={'REQUIRE_PARTS': ['month', 'day']})

    #OK: Integer is Ignored, no datetime returned
    parse('30', settings={'REQUIRE_PARTS': ['month', 'day']})

    #NOT OK: Datetime Should be Found
    parse('Today is the most wonderful 30th of March', settings={'REQUIRE_PARTS': ['month', 'day']})


    It would be great if I could combine the fuzzy=True argument from the dateutils module with the settings argument from the dateparser module, but seeing as they are separate modules, that is not feasible.

    Is there another way to achieve the same functionality?

    Continue reading...

Compartilhe esta Página