Search code examples
python-3.xstrptime

Convert string to date python strptime error


I tried to convert this date string: Wed May 23 15:45:43 +0000 2018 to a python date object with strptime. I checked how I'm supposed to use it but I definitely don't understand where my problem is.

I just tried this

date = datetime.strptime('Wed May 23 15:45:43 +0000 2018', '%a %b %d %x %z %Y')

It suppose to be in the right format but I got this error:

sre_constants.error: redefinition of group name 'd' as group 5; was group 3 at position 169

Does it mean that 23 isn't a %d format ?

Thanks for your help


Solution

  • Your format doesn't match the date string. To know more about the format refer to this https://docs.python.org/2/library/datetime.html. I have made the correct format for your code. Here is the working code

    from datetime import datetime
    date = datetime.strptime('Wed May 23 15:45:43 +0000 2018',
                             '%a %b %d %H:%M:%S %z %Y')
    print(date) # Output 2018-05-23 15:45:43+00:00
    

    Working code is here https://ideone.com/ONDSyD