如何解析日期(928142400000 + 0200)?

时间:2014-11-04 09:40:41

标签: python json rest python-datetime datetime-parsing

我有JSON响应对象,字符串表示日期和时间:

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

我不确定:

  • 是什么格式
  • 我如何在python应用程序中解析它
  • 如何将python日期转换为此格式

有什么建议吗?

1 个答案:

答案 0 :(得分: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)))