문제

I had an earlier question, which I have deleted in favour of this one. Since I was under the wrong assumption that it had something to do with the dateutil version.

test1 = dateutil.parser.parse("2013-01-24T16:50:42+00:00")  

this works fine and I get a datetime.

But

dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None
test2 =  json.dumps(event.due_date_time, default=dthandler)

print test2 --> "2013-01-24T16:50:42+00:00"

This looks to me like a normal string

test3 = dateutil.parser.parse(test2)

This crashes saying ValueError: unknown string format

So how do I convert json string into 'normal' string?

도움이 되었습니까?

해결책

You are forgetting that JSON puts quotes around the string. You have the following value:

jsonvalue = '"2013-01-24T16:50:42+00:00"'

Note the double quotes there.

You'd need to load that value using the json.loads() method again, which in this case just removes the quotes again:

>>> print json.loads(jsonvalue)
2013-01-24T16:50:42+00:00

Note that now the quotes are gone again. You could also just strip the quotes with .strip('"') if you have a mix:

>>> print jsonvalue.strip('"')
2013-01-24T16:50:42+00:00

but since you are expecting JSON data, why not just treat it as json data and use the json module for this to turn it back to Python data.

다른 팁

The quotes are in the string (print doesn't add them).

So test3 = dateutil.parser.parse(test2[1:-1]) will work.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top