1

I'm trying to parse a basic iso formatted datetime string in Python, but I'm having a hard time doing that. Consider the following example:

>>> import json
>>> from datetime import datetime, date
>>> import dateutil.parser
>>> date_handler = lambda obj: obj.isoformat()
>>> the_date = json.dumps(datetime.now(), default=date_handler)
>>> print the_date
"2017-02-18T22:14:09.915727"
>>> print dateutil.parser.parse(the_date)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    print dateutil.parser.parse(the_date)
  File "/usr/local/lib/python2.7/site-packages/dateutil/parser.py", line 1168, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/dateutil/parser.py", line 559, in parse
    raise ValueError("Unknown string format")
ValueError: Unknown string format

I've also tried parsing this using the regular strptime:

>>> print datetime.strptime(the_date, '%Y-%m-%dT%H:%M:%S')
# removed rest of the error output
ValueError: time data '"2017-02-18T22:11:58.125703"' does not match format '%Y-%m-%dT%H:%M:%S'
>>> print datetime.strptime(the_date, '%Y-%m-%dT%H:%M:%S.%f')
# removed rest of the error output
ValueError: time data '"2017-02-18T22:11:58.125703"' does not match format '%Y-%m-%dT%H:%M:%S.%f'

Does anybody know how on earth I can parse this fairly simple datetime format?

1
  • Why did you use json.dumps on it? If you have JSON, parse it before parsing the date. Commented Feb 18, 2017 at 21:19

1 Answer 1

6

note the error message:

ValueError: time data '"2017-02-18T22:11:58.125703"'

There are single quotes + double quotes which means that the string actually contains double quotes. That's because json serialization adds double quotes to strings.

you may want to strip the quotes around your string:

datetime.strptime(the_date.strip('"'), '%Y-%m-%dT%H:%M:%S.%f')

or, maybe less "hacky", de-serialize using json.loads:

datetime.strptime(json.loads(the_date), '%Y-%m-%dT%H:%M:%S.%f')
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I overlooked that. Thanks!

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.