Search code examples
pythonpython-2.7datetimestrptime

Converting a readable date & time string to a datetime object in Python


I am trying to convert a date and time string such as "Mar 15, 2016 10:47:15" into a Python datetime object using strptime. I believe I have the formatting correct however I still get a ValueError exception when I run the below:

>>> s = "Mar 15, 2016 10:47:15"
>>> datetime.datetime.strptime(s,"%b %m, %Y %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Mar 15, 2016 10:47:15' does not match format '%b %m, %Y %H:%M:%S'

Any ideas as to what may be wrong with my format string?


Solution

  • The second item in the format string (%m) refers to month. Changing it to %d will make your code work.

    datetime.datetime.strptime(s,"%b %d, %Y %H:%M:%S")
    

    Here are the relevant parts from strptime documentation:

    %d Day of the month as a zero-padded decimal number. 01, 02, ..., 31

    %m Month as a zero-padded decimal number. 01, 02, ..., 12