Search code examples
pythondatetimestrptime

Converting date and time from String format to Python datetime object: ValueError: time data '... p.m.' does not match format '... %p'


I have date and time in the below String format:

dateTime = '21-03-2015 12:20 p.m.'

And I want to convert it into Python datetime object. I'm doing something like below:

dateTimeObj = datetime.datetime.strptime(dateTime, '%d-%m-%Y %I:%M %p')

But I keep getting the below error:

ValueError: time data '21-03-2015 12:20 p.m.' does not match format '%d-%m-%Y %I:%M %p'

Just don't seem to get what I'm doing wrong. Any solutions would be greatly appreciated.


Solution

  • As per the documentation the %p supports AM, PM, am or pm format only so a.m., a m , etc are not supported formats. Now the problem is in the format of date you are trying, If you are not able to change the format of the date then you can use:

    import datetime
    
    d = '21-03-2015 12:20 p.m.'
    
    d = d.replace(".", "")    #Substituting the periods with ""
    
    dateTimeObj = datetime.datetime.strptime(d, '%d-%m-%Y %I:%M %p')