Reputation: 3612
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)/
which json.parse just parses out as a string. How can I convert this to a python date time object?
Edit: 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.
Upvotes: 3
Views: 9829
Reputation: 749
I couldn't add this to the comments of moonsly's answer (no rep), so I made it a separate answer. Just wanted to add a few things others may find useful. I had this same issue but the json dates were appearing in my data a little differently (ie no + sign):
/Date(1416458650000)/
There are 9 or 13 character strings. The 9 char strings don't need to be divided by 1000.0. I also didn't use regex to extract the time string.
MILLISECONDS = '/Date(1416458650000)/'.split('(')[1][:-2]
print datetime.datetime.fromtimestamp(int(MILLISECONDS)/1000.0).strftime('%Y-%m-%d %H:%M:%S')
2014-11-20 15:44:10
I can also do
SECONDS = '/Date(1416458650000)/'.split('(')[1][:-5]
print datetime.datetime.fromtimestamp(float(SECONDS)).strftime('%Y-%m-%d %H:%M:%S')
2014-11-20 15:44:10
Upvotes: 1
Reputation: 1391
Have you checked Convert JSON to Python object: how to handle DateTime conversion??
This looks very similar - and an alternative way to what moonsly provided, although, I think moonsly has provided a more 'pythonic' approach than what is provided in the other similar thread (IMO)
Upvotes: 1
Reputation: 612
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: note , that you also have milliseconds in this date, they will be truncated by this code
Upvotes: 5