3

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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

What should be the other way around...given that I have mm-yyyy formatted date and I want to convert it into a date object like xxxxxxxxx ..?
In order to read negative number (i.e.date before 1 Jan 1970) change regex to like re.search(r"Date(([+-]\d+)\+", 'Date(1354011247940+0000)') Please note added [+-] to read the sign.
1

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)

1 Comment

Yes, I looked at that - but the accepted (and only) answer says to change the format of the string when serializing, which is not an option here. I have no control over the data or how it is serialized.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.