Reputation: 387
I want to convert a string to a datetime in Python. But there are some characters, which are irrelevant in the String.
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)
my_format
?Thanks in advance.
Upvotes: 3
Views: 773
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