【问题标题】:How to get expiry date from cookies?如何从 cookie 中获取有效期?
【发布时间】:2019-07-06 20:00:29
【问题描述】:

我正在尝试从由 Set-Cookie 标头设置的网站中解析 cookie 的有效期。我正在使用 requests 库,这就是我的进步:

import requests

req = requests.get(url, headers=headers)
if req.cookies:
    for cook in req.cookies:
        if cook.expires: # checking the expires flag
            print('Cookie Expiry Time: %s' % (cook.expires))

但是,cook.expires 返回一个难以理解的值,例如 21811839941550035594。接下来需要做什么才能从 expires 标志中获取确切的日期时间值?

【问题讨论】:

    标签: python python-3.x cookies python-requests setcookie


    【解决方案1】:

    您获得的cook.expires 值是一个时间戳值。您只需要使用datetime 库中的fromtimestamp() 即可解决此问题。这是您的代码:

    import requests
    from datetime import datetime
    
    req = requests.get(url, headers=headers)
    if req.cookies:
       for cook in req.cookies:
           if cook.expires: # checking the expires flag
               print(datetime.fromtimestamp(cook.expires))
    

    例如,如果您的 url 是 https://github.com,您将获得人类可读的格式:

    2039-02-13 10:30:14 # expiry date for first cookie
    2019-02-13 11:30:14 # expiry date for second cookie
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2012-02-02
      • 2014-10-02
      相关资源
      最近更新 更多