0

String :- "Today is November 19th, 2019."

Output :- November 19th, 2019

I tried this :-

datetime.strptime(re.search((January|February|March|April|May|June|July|August|September|Octomber|November|December) \d{1,2}(th|st|rd), \d{4}",String).group(), "%B %d, %Y")

But it shows me Error like :-

ValueError: time data 'November 11th, 2019' does not match format '%B %d(th|st|rd), %Y'

Can anyone help me in this , Where I am wrong .

blhsing
  • 91,368
  • 6
  • 71
  • 106
Learner
  • 13
  • 5

1 Answers1

1

The datetime formatting does not support regex-like patterns, so you should build a string of a fixed format first for it parse.

You can use re.sub instead to extract only the month, day and year from the string and reassemble them into a space-delimited string before passing to datetime.strptime for parsing:

datetime.strptime(re.sub(r'.*\b(January|February|March|April|May|June|July|August|September|Octomber|November|December) (\d{1,2})(?:th|st|rd), (\d{4})\b.*', r'\1 \2 \3', String), "%B %d %Y")
blhsing
  • 91,368
  • 6
  • 71
  • 106