Converting ASP.Net JSON Date into Python datetime [duplicate]

白昼怎懂夜的黑 提交于 2019-12-01 21:56:02

问题


I am getting a response from the rest is an time format like

ScheduleDate = "\/Date(1374811200000-0400)\/"
StartTime = "\/Date(-2208931200000-0500)\/"

How could I convert the above time to format like

"2012-01-01T10:30:00-05:00"

回答1:


This is what I came up with, but neither of your example inputs matched up to your example output so I'm not sure whether there's a timezone offset error here or not.

#!/usr/bin/env python

import datetime

def parse_date(datestring):
    timepart = datestring.split('(')[1].split(')')[0]
    milliseconds = int(timepart[:-5])
    hours = int(timepart[-5:]) / 100
    time = milliseconds / 1000

    dt = datetime.datetime.utcfromtimestamp(time + hours * 3600)
    return dt.strftime("%Y-%m-%dT%H:%M:%S") + '%02d:00' % hours

ScheduleDate = "\/Date(1374811200000-0400)\/"
StartTime = "\/Date(-2208931200000-0500)\/"

print(parse_date(ScheduleDate))
print(parse_date(StartTime))

It seems to be the case that Windows doesn't like negative values in datetime.(utc)?fromtimestamp(). It may be possible to ask it to compute a negative time delta from the Unix epoch:

#!/usr/bin/env python

import datetime

EPOCH = datetime.datetime.utcfromtimestamp(0)

def parse_date(datestring):
    timepart = datestring.split('(')[1].split(')')[0]
    milliseconds = int(timepart[:-5])
    hours = int(timepart[-5:]) / 100
    adjustedseconds = milliseconds / 1000 + hours * 3600

    dt = EPOCH + datetime.timedelta(seconds=adjustedseconds)
    return dt.strftime("%Y-%m-%dT%H:%M:%S") + '%02d:00' % hours

ScheduleDate = "\/Date(1374811200000-0400)\/"
StartTime = "\/Date(-2208931200000-0500)\/"

print(parse_date(ScheduleDate))
print(parse_date(StartTime))


来源:https://stackoverflow.com/questions/18039625/converting-asp-net-json-date-into-python-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!