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.

Community
  • 1
  • 1
ibrewster
  • 3,482
  • 5
  • 42
  • 54

3 Answers3

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

moonsly
  • 612
  • 6
  • 11
  • 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 ..? – user2480542 Jul 08 '13 at 16:55
  • 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. – Softec May 08 '19 at 09:51
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)

Community
  • 1
  • 1
Justin Carroll
  • 1,362
  • 1
  • 13
  • 37
  • 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. – ibrewster Nov 27 '12 at 20:12
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
knowingpark
  • 639
  • 7
  • 16