2014-11-04 15 views
1

我有一個字符串表示的日期和時間JSON響應對象:如何解析日期(928142400000 + 0200)?

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

我不知道:

  • 什麼格式是
  • 我怎樣才能解析它在Python應用程序
  • 如何將python日期轉換爲此格式

任何建議離子?

+0

也許你可以看到你在找什麼[這裏](http://stackoverflow.com/questions/13591858/how-to-parse-json-datetime-string-in-python)。 – TioDavid 2014-11-04 09:43:53

回答

3

928142400000是自UNIX紀元以來的毫秒數,+0200是時區。

隨着dateutil librarydatetime.timezone() objects你可以模擬的時區偏移,時間戳本身是可解析與datetime.datetime.fromtimestamp(),只要你通過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) 

dateutil.tz.tzoffset() object版本是相似的:

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) 

演示:

>>> 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))) 
+0

答案中有一個括號。 – 2014-11-04 09:52:18

+0

@MauroBaraldi:早已逝去,謝謝! – 2014-11-04 10:00:50