'How to extract date out of string using date time

if for example I have a string like this

import datetime as datetime
string = "Hello todays date is 11/02/2022 thanks"

How may I use datetime to extract just the date and display is as Nov/2/2022. Thanks in advance for any help.



Solution 1:[1]

Using python-dateutil:

In [1]: import dateutil.parser as dparser

In [18]: dparser.parse("Hello todays date is 11/02/2022 thanks", fuzzy=True)
Out[18]: datetime.datetime(2022, 11, 02, 0, 0)

Solution 2:[2]

Checkout this article.

In your case solution looks like:

datetime_object = datetime.strptime(
    string,
    "Hello todays date is %m/%d/%Y thanks"
)

Solution 3:[3]

Using only the standard library, you can find the date using a regex and then parse it with datetime.

import datetime
import re

string = "Hello todays date is 11/02/2022 thanks"

m = re.search(r"\d\d/\d\d/\d\d\d\d", string)

if m:
    print(datetime.datetime.strptime(m[0], "%d/%m/%Y"))

Solution 4:[4]

Firstly, you need to import like this

from datetime import datetime

You can then use regex to get the date:

import re
string = "Hello todays date is 11/02/2022 thanks"
regex = re.findall(r'\d{2}\/\d{2}\/\d{2}', string)

This will return a list of all matches. You can then convert the matched strings:

d_time = datetime.strptime(regex[0], '%m/%d/%y')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nathan Getty
Solution 2 Andrey Naradzetski
Solution 3 ljmc
Solution 4 StBlaize