计算ISO 8601的日期时间差

时间:2018-12-18 00:18:36

标签: python python-3.x

我正在努力正确地处理某些日期时间值。我们有一个SaaS提供程序,它使用429的HTTP响应代码来实现其API,这意味着我们已经超出了他们的使用率,并且要退后。它们在“ X-RateLimit-Reset”中传递标头,该标头的值是重置请求时的ISO8601日期戳。我正在尝试采用该值,然后采用“现在”并计算我必须等待的时间(以秒为单位)。到目前为止,我已经构建了以下代码:

    elif ask.status_code == 429:
        print("API rate limit hit. Resting...")

        # ask.headers['X-RateLimit-Reset'] is passed back with a ISO8601 time stamp of when the api limit will be reset.
        # example: “2016-12-13T18:38:00Z”
        a = time.strptime(ask.headers['X-RateLimit-Reset'], '%Y-%m-%dT%H:%M:%SZ')
        a = time.mktime(a)

        print(ask.headers['X-RateLimit-Reset'])

        # I don't get this...
        myTZ = datetime.tzinfo
        myTZ.timezone.utc

        # Calculate the offset taking into account daylight saving time
        b = datetime.utcnow().replace(tzinfo=myTZ.timezone.utc).replace(microsecond=0).isoformat()
        b = time.strptime(b, '%Y-%m-%dT%H:%M:%S%z')
        b = time.mktime(b)

        # Time in seconds to wait and retry
        apiReset = (b-a)+1

        print("Sleeping {} seconds".format(apiReset))
        time.sleep(apiReset)

        return self.CallAPI(uri, method, data, timeout)

它只是没有按照我的需要去做。我已经消除了一些例外,但现在我只能解决这个例外:

API rate limit hit. Resting...
2018-12-18T00:07:54Z
Traceback (most recent call last):
  File "Development/evident.io/mainbody.py", line 22, in <module>
    EvidentIO.ListSubORGs()
  File "/Users/i864248/OneDrive - SAP         SE/Development/evident.io/evidentio.py", line 112, in ListSubORGs
    return self.APICallHandler('/api/v2/sub_organizations')
  File "/Users/i864248/OneDrive - SAP     SE/Development/evident.io/evidentio.py", line 297, in APICallHandler
    response = self.CallAPI(uri, method, data, timeout)
  File "/Users/i864248/OneDrive - SAP SE/Development/evident.io/evidentio.py", line 407, in CallAPI
    myTZ.timezone.utc
AttributeError: 'getset_descriptor' object has no attribute 'timezone'

有人可以帮我吗?也许我甚至一开始都不正确地做?

1 个答案:

答案 0 :(得分:0)

好的,当然在发布此消息后不久,我发现了一个不错的解决方案。在其他地方使用一些示例,我将代码简化为:

a = datetime.strptime(ask.headers['X-RateLimit-Reset'], '%Y-%m-%dT%H:%M:%SZ')
timestamp = (a - datetime(1970, 1, 1)).total_seconds()

ts = time.time()
timeDiff = (timestamp - ts)

print("Sleeping for {} seconds".format(timeDiff))
time.sleep(timeDiff + 1) 
print("Continuing")
return self.CallAPI(uri, method, data, timeout)

这似乎很好。