将JSON转换为Python对象:如何处理DateTime转换? [英] Convert JSON to Python object: how to handle DateTime conversion?
问题描述
我有一个C#控制台应用程序,它将POCO类序列化为JSON字符串;我使用JSON.Net进行序列化.
I have a C# console app that serializes a POCO class to a JSON string; I use JSON.Net for serialization.
此应用程序中的JSON被转储到文件中,并由Python 2.7脚本读取.
The JSON from this app is dumped to a file, and read in by a Python 2.7 script.
这是问题所在. JSON序列化将类中的所有datetime属性都转换为以下格式:
Here's the problem. The JSON serialization takes all the datetime properties on my class and converts them to this format:
/Date(1322856016353-0500)/
当我使用json.parse时;我收到了与Python原始班级相当的成果;除了所有的DateTime属性,现在都是包含"/Date(1322856016353-0500)/"而不是Python datetime字段的字符串.
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.
似乎我需要手动从字符串中解析时间并手动创建datetime obj.在我这样做之前;有一个更好的方法吗?也许我可以将DateTime属性以另一种格式序列化为JSON?还是使用其他Python JSON解析器?
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.
谢谢, 弗兰克
推荐答案
您可以指定所需的格式.尝试这样的事情:
You can specify the format you want. Try something like this:
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
序列化之前:
time = datetime.strftime(time, DATETIME_FORMAT)
反序列化后:
time = datetime.strptime(time, DATETIME_FORMAT)
这篇关于将JSON转换为Python对象:如何处理DateTime转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!