time data 'May 10 2021' does not match format '%m %d %Y'

Viewed 2094

I am having trouble printing a formatted time object produced from a string

This is my code:

date_time_str = 'May 10 2021'
date_time_obj = datetime. strptime(date_time_str, '%m %d %Y')
print("The type of the date is now", type(date_time_obj))

This is the error:
ValueError: time data 'May 10 2021' does not match format '%m %d %Y'
2 Answers

As per This link, for a month in the Month format, you need to use %B , and for a month in the Mth format ('Apr','Jun') , use %b.

You were using %m, which is used for numerical numbers.

The below works as an example:

import time
import datetime
from time import strptime
print("hello world")
date_time_str = 'May 10 2021'
date_time_obj = strptime(date_time_str, '%B %d %Y')
print("The type of the date is now", date_time_obj)

You can also use datetime parser from dateutil package with fuzzy parsing which is extremely useful when parsing non-standard datetime formats or parsing dates from text:

from dateutil import parser as dps

>>> a = 'Today is 11th of June 2021'
>>> d = dps.parse(a, fuzzy=True)
>>> d
Out[5]: datetime.datetime(2021, 6, 11, 0, 0)

>>> b = 'May 10, 2021'
>>> c = dps.parse(b, fuzzy=True)
>>> c
Out[8]: datetime.datetime(2021, 5, 10, 0, 0)
Related