Search code examples
pythondatetimestrptime

Value Error in Python when converting string to date using datetime.strptime


I have a string variable named dte that prints in the following format:

Tue Feb 13 23:49:10 +0000 2018

I'm trying to convert it to a date type so that I can work out how long ago it was in days, hours, minutes etc but keep getting the following error:

ValueError: time data 'Tue Feb 13 23:49:10 +0000 2018' does not match format '%a %b %d %I:%M:%S %z %Y'

I'm using this code:

new_date = datetime.datetime.strptime(dte, "%a %b %d %I:%M:%S %z %Y")
print(new_date)

I've tried removing the colons but get the same error. I'm sure it's something very simple I'm overlooking but can't figure out what it is.

Any help appreciated.


Solution

  • You need %H for the hour component not %I:

    In[8]:
    dte="Tue Feb 13 23:49:10 +0000 2018"
    new_date = dt.datetime.strptime(dte, "%a %b %d %H:%M:%S %z %Y")
    new_date
    
    Out[8]: datetime.datetime(2018, 2, 13, 23, 49, 10, tzinfo=datetime.timezone.utc)
    

    You have 24-hour hour component, not 12-hour which is what %I is for, see the docs