Search code examples
pythondatetimepython-datetime

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


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'

Solution

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