0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ugh, can't believe I missed that! Cheers
0

Month name is locale-specific. If you want to use english months names set for application English-based locale like en_US.

    $ env LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8 python
    >>> import datetime
    >>> s = "Mar 15, 2016 10:47:15"
    >>> datetime.datetime.strptime(s,"%b %d, %Y %H:%M:%S")
    datetime.datetime(2016, 3, 15, 10, 47, 15)

P.S. %m replaced with %d, which means day.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.