1

我正在使用两个时间戳来确定 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 接受的正确格式。

4

1 回答 1

2

您不能将字符串传递到relativedelta. 它需要你传入datetime.datetimedatetime.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)
于 2013-09-26T06:57:58.717 回答