3

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.

  • I know that I can change the string (remove the irrelevant characters) first like
raw_str = "2018-01-01Ajrwoe"
my_str = raw_str[:10]
strptime(my_str, my_format)
  • But I just want to directly match the arbitrary characters like
raw_str = "2018-01-01Ajrwoe"
strptime(raw_str, my_format)
  • But how is my_format?

Thanks in advance.

2

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.