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.

TrW236
  • 367
  • 1
  • 5
  • 14
  • Possible duplicate of [datetime strptime - set format to ignore trailing part of string](https://stackoverflow.com/questions/29284850/datetime-strptime-set-format-to-ignore-trailing-part-of-string) – wilkben Aug 22 '19 at 12:24
  • Take a look here: https://stackoverflow.com/a/5045374/11703358 – ipaleka Aug 22 '19 at 12:33

2 Answers2

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)
vlemaistre
  • 3,301
  • 13
  • 30
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))
Lufftre
  • 118
  • 1
  • 2
  • 8