TrW236
TrW236

Reputation: 387

How to match arbitrary characters in a str when formatting datetime in Python?

I want to convert a string to a datetime in Python. But there are some characters, which are irrelevant in the String.

Python Datetime Document

Is the official document, there is no clear way to match arbitrary characters in the String.


For example, I have a String 2018-01-01Ajrwoe.

I want to convert this string into a datetime as 2018 (year) 01 (month) and 01 (day).

The rest of this string is irrelevant.

raw_str = "2018-01-01Ajrwoe"
my_str = raw_str[:10]
strptime(my_str, my_format)
raw_str = "2018-01-01Ajrwoe"
strptime(raw_str, my_format)

Thanks in advance.

Upvotes: 3

Views: 773

Answers (2)

vlemaistre
vlemaistre

Reputation: 3331

Here is a way to do it using a regex to clean your string :

raw_str = "2018-01-01Ajrwoe"

datetime.datetime.strptime(re.sub('[a-z|A-Z]', '', raw_str), '%Y-%m-%d')

Output :

datetime.datetime(2018, 1, 1, 0, 0)

Upvotes: 1

Lufftre
Lufftre

Reputation: 130

You could match the date using a regex.

For example:

import re
raw_str = "2018-01-01Ajrwoe"
match = re.search(r'\d+-\d+-\d+', raw_str)
print(match.group(0))

Upvotes: 0

Related Questions