Home > front end >  How to identify multiple dates within a python string?
How to identify multiple dates within a python string?

Time:01-28

For a given string, I want to identify the dates in it.

import datefinder
string = str("/plot 23/01/2023 24/02/2021 /cmd")

matches = list(datefinder.find_dates(string))

if matches:
    print(matches)
else:
    print("no date in string")

Output:

no date in string

However, there are clearly dates in the string. Ultimately I want to identify which date is the oldest by putting in a variable Date1, and which date is the newest by putting in a variable Date2.

CodePudding user response:

I believe that if a string contains multiple dates, datefinder is unable to parse it. In your case, splitting the string using string.split() and applying the find_dates method should do the job.

CodePudding user response:

You've only given 1 example, but based on that example, you can use regex.

import re
from datetime import datetime

string = "/plot 23/01/2023 24/02/2021 /cmd"
dates = [datetime.strptime(d, "%d/%m/%Y") for d in re.findall(r"\d{2}/\d{2}/\d{4}", string)]
print(f"earliest: {min(dates)}, latest: {max(dates)}")

Output

earliest: 2021-02-24 00:00:00, latest: 2023-01-23 00:00:00
  • Related