1

I have JSON response object with string representing date and time:

"event":{
    "type":"Type",
    "date-time":"\/Date(928142400000+0200)\/",
},

I am not sure:

  • what format is that
  • how can I parse it in python app
  • how can I convert python date into this format

Any suggestions?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
dease
  • 2,975
  • 13
  • 39
  • 75
  • Maybe you can see what you are looking for [here](http://stackoverflow.com/questions/13591858/how-to-parse-json-datetime-string-in-python). – TioDavid Nov 04 '14 at 09:43

1 Answers1

4

928142400000 is the time in milliseconds since the UNIX epoch, +0200 is the timezone.

With the dateutil library or datetime.timezone() objects you can model the timezone offset, the timestamp itself is parsable with datetime.datetime.fromtimestamp(), provided you divide the value by 1000.0:

import datetime
import re

timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
timestamp, offset = timestamp_parse.search(datetime_value).groups()
tzoffset = datetime.timedelta(hours=int(offset[1:3]), minutes=int(offset[3:]))
if offset[0] == '-':
    tzoffset *= -1
tzoffset = datetime.timezone(tzoffset)
dt = datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)

The dateutil.tz.tzoffset() object version is similar:

import datetime
import re
import dateutil.tz

timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
timestamp, offset = timestamp_parse.search(datetime_value).groups()
tzoffset = int(offset[1:3]) * 3600 + int(offset[3:]) * 60
if offset[0] == '-':
    tzoffset *= -1
tzoffset = dateutil.tz.tzoffset(None, tzoffset)
dt = datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)

Demo:

>>> import datetime
>>> import re
>>> datetime_value = "/Date(928142400000+0200)/"
>>> timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
>>> timestamp, offset = timestamp_parse.search(datetime_value).groups()
>>> tzoffset = datetime.timedelta(hours=int(offset[1:3]), minutes=int(offset[3:]))
>>> if offset[0] == '-':
...     tzoffset *= -1
... 
>>> tzoffset = datetime.timezone(tzoffset)
>>> datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)
datetime.datetime(1999, 5, 31, 10, 20, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343