Date conversion .NET JSON to ISO

后端 未结 4 939
孤城傲影
孤城傲影 2020-12-03 19:32

How can I convert a date time format from JSON.Net such as:

/Date(1154970000000+0700)/

To ISO-?? format 2011-12-18T23:34:59Z

Preferably in either Pyt

4条回答
  •  失恋的感觉
    2020-12-03 19:54

    Here's a little class I wrote years ago to clean up this sort of invalid JSON that some .NET library generates:

    class DotNETDecoder(simplejson.JSONDecoder):
        '''
        This is a decoder to convert .NET encoded JSON into python objects
        The motivation for this is the way .NET encodes dates.
        See:
        https://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2
        .NET encodes datetimes like this: "\/Date(628318530718)\/"
        '''
    
        def __init__(self, timezone, *args, **kwargs) -> None:
            super().__init__(*args, **kwargs)
            self.parse_string = self._date_parse_string(timezone)
            self.scan_once = py_make_scanner(self)
    
        @staticmethod
        def _date_parse_string(timezone):
            def _parse_string(string, idx, encoding, strict):
                obj = scanstring(string, idx, encoding, strict)
                if isinstance(obj[0], str):
                    match = date_match.search(obj[0])
                    if match:
                        return [dt.datetime.fromtimestamp(
                                    int(match.group(1)) / 1000, timezone),
                                obj[1]]
                return obj
            return _parse_string
    

    And a test case / example:

    def test_can_decode_dotnet_json_dates():                                                                                                                                                                     
        jsonstr = '{"date": "Date(1330848000000)", "f": "b", "l": [], "i": 5}'                                                                                                                                   
        timezone = pytz.timezone('America/New_York')                                                                                                                                                             
        obj = json.loads(jsonstr, cls=DotNETDecoder, timezone=timezone)                                                                                                                                          
        assert obj['date'] == timezone.localize(dt.datetime(2012, 3, 4, 3, 0))                                                                                                                                   
        assert obj['f'] == "b"                                                                                                                                                                                   
        assert obj['i'] == 5                                                                                                                                                                                     
        assert obj['l'] == []
    

提交回复
热议问题