Convert JSON to Python object: how to handle DateTime conversion?
-
27-10-2019 - |
Question
I have a C# console app that serializes a POCO class to a JSON string; I use JSON.Net for serialization.
The JSON from this app is dumped to a file, and read in by a Python 2.7 script.
Here's the problem. The JSON serialization takes all the datetime properties on my class and converts them to this format:
/Date(1322856016353-0500)/
When I use json.parse; I receive the equivalent of my original class in Python; except all of the DateTime properties are now strings containing "/Date(1322856016353-0500)/" instead of Python datetime fields.
It looks like I'm going to need to manually parse the time out of the string and create a datetime obj manually. Before I do that; is there a better way to do this? Perhaps I could serialize the DateTime properties to JSON in another format? Or use a different Python JSON parser?
Any constructive input is greatly appreciated.
Thanks, Frank
Solution
You can specify the format you want. Try something like this:
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
Before serializing:
time = datetime.strftime(time, DATETIME_FORMAT)
After unserializing:
time = datetime.strptime(time, DATETIME_FORMAT)