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.
CodePudding user response:
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)
CodePudding user response:
Checkout this article.
In your case solution looks like:
datetime_object = datetime.strptime(
string,
"Hello todays date is %m/%d/%Y thanks"
)
CodePudding user response:
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"))
CodePudding user response:
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')