我使用两个时间戳来确定views.py文件中djnago项目的延迟:
import datetime
import dateutil.relativedelta
def get_diff(url, header) :
enc_data = utils.http_response('get', url, header)['body']
json_data = json.loads(enc_data)['data']
timestamp = json_data[0]["timestamp"].split('.')[0].split("T")
lastModified = json_data[0]["lastModified"].split('.')[0].split("T")
timestamp = timestamp[0]+ ":" + timestamp[1]
lastModified = lastModified[0] + ":" +lastModified[1]
print json_data[0]
print timestamp , lastmodified
diff = dateutil.relativedelta.relativedelta(lastModified, timestamp)
return diff
这在终端上给出了错误:
{u'applicationName': u'None', u'userName': u'LocalHardcodedUser', u'facilityId': None, u'resource': u'pat', u'parameters': {u'limit': u'10', u'name': u'sdgds'}, u'accessToken': u'6FDG-TR08', u'lastModified': u'2013-09-26T02:59:14.436562',
u'uri': u'/v1/pat/519b/clinical', u'method': u'GET', u'requestBody': u'', u'visitNumber': None, u'mr': None, u'timestamp': u'2013-09-25T11:48:01.074000', u'message': u'name', u'rrt': None, u'type': u'error', u'id', u'5242cd71c83', u'statusCode': 500}
2013-09-25:11:48:01 2013-09-26:02:40:03 #output of **print timestamp , lastmodified**
Internal Server Error: /v1/ready
Traceback (most recent call last):
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/arya/apps/hma/views.py", line 538, in get_health_check
diff= get_diff
File "/home/arya/apps/hma/views.py", line 531, in get_diff
print dateutil.relativedelta.relativedelta(lastModified, timestamp)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/dateutil/relativedelta.py", line 118, in __init__
raise TypeError("relativedelta only diffs datetime/date")
TypeError: relativedelta only diffs datetime/date
请任何人解释relativedelta接受的正确格式。
答案 0 :(得分:2)
您无法将字符串传递给relativedelta
。它要求您传递datetime.datetime
或datetime.date
个对象。
您的JSON数据包含ISO8601格式时间戳,这是可解析的最可解析格式。您已经拥有dateutil
库,只需使用它来解析字符串:
import dateutil.relativedelta
import dateutil.parser
def get_diff(url, header) :
enc_data = utils.http_response('get', url, header)['body']
json_data = json.loads(enc_data)['data']
timestamp = dateutil.parser.parse(json_data[0]["timestamp"])
lastModified = dateutil.parser.parse(json_data[0]["lastModified"])
diff = dateutil.relativedelta.relativedelta(lastModified, timestamp)
return diff
演示:
>>> import dateutil.parser
>>> import dateutil.relativedelta
>>> timestamp = dateutil.parser.parse('2013-09-25T11:48:01.074000')
>>> lastModified = dateutil.parser.parse('2013-09-26T02:59:14.436562')
>>> dateutil.relativedelta.relativedelta(lastModified, timestamp)
relativedelta(hours=+15, minutes=+11, seconds=+13, microseconds=+362562)