如何在python中解析JSON datetime字符串? [英] How to parse JSON datetime string in python?
问题描述
我正在从python调用远程API,该API返回JSON格式的数据.然后,我使用带有json.loads()的json模块解析数据.我遇到的问题是日期-我正在调用的系统返回的日期格式如下:
From python I am making a call to a remote API which returns data in a JSON format. I then parse the data using the json module with json.loads(). The problem I am having is with dates - the system I am calling returns the date formatted like the following:
/Date(1354011247940+0000)/
哪个json.parse只是解析为一个字符串.如何将其转换为python日期时间对象?
which json.parse just parses out as a string. How can I convert this to a python date time object?
不同于将JSON转换为Python对象:如何处理DateTime转换?,我无法控制正在发送的数据,因此不能简单地在序列化之前更改格式.
unlike Convert JSON to Python object: how to handle DateTime conversion?, I have no control over the data being sent, so I can not simply change the format prior to serializing.
推荐答案
您应该从该日期开始获取带有正则表达式的unix时间戳,然后使用datetime模块将其转换为可读格式:
You should get unix timestamp with a regex from this date, then use datetime module to convert it to readable format:
>m = re.search(r"Date\((\d+)\+", 'Date(1354011247940+0000)')
>print(datetime.datetime.fromtimestamp(int(m.group(1))/1000.0).strftime('%Y-%m-%d %H:%M:%S'))
2012-11-27 12:14:07
UPD:请注意,该日期您还有毫秒,该代码将把它们截断
UPD: note , that you also have milliseconds in this date, they will be truncated by this code
这篇关于如何在python中解析JSON datetime字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!