首页 > 解决方案 > 将 UNIX 时间戳转换为以秒为单位的时间长度

问题描述

我正在做一个项目,我需要帮助。

我想计算多久前发布了一张 instagram 图片。使用他们的 json api,我可以举个例子:

      "edge_owner_to_timeline_media": {
    "count": 19938,
    "page_info": {
      "has_next_page": true,
      "end_cursor": "AQCJsPghTApTJTITHUm_iXp9fqZGXrfJXIYCc60OqvLM98v9a8xgDQ8hiIUUaViSd913BxRHSILvz8_G2Vfw0FALXEFEf2p2fpuNnupbvjqQ8A"
    },
    "edges": [
      {
        "node": {
          "__typename": "GraphImage",
          "id": "1825727462006678242",
          "edge_media_to_caption": {
            "edges": [
              {
                "node": {
                  "text": "Yep"
                }
              }
            ]
          },
          "shortcode": "BlWSXQdlWLi",
          "edge_media_to_comment": {
            "count": 9
          },
          "comments_disabled": false,
          "taken_at_timestamp": 1531863695,
          "dimensions": {
            "height": 1080,
            "width": 1080
          },

亮点是“taken_at_timestamp”,它在 UNIX 时间上传图像时给了我,但是我想做的是通过示例获取当前的 UNIX 时间:

import time
int(time.time()) 

然后以秒为单位计算图像从现在上传多久(与时区无关)?那可能吗?我很难理解 UNIX 和 Epoch 时代以及所有这些 :)

标签: pythonpython-3.xunixtimeunix-timestamp

解决方案


只需减去taken_at_timestamptime.time()秒为单位获得两次之间的差异。

import time

# I don't know your full json layout, so you will need to substitute this.
edges = data["edge_owner_to_timeline_media"]["edges"]

taken_at = edges[0]["taken_at_timestamp"]

age = time.time() - taken_at
print(age, "seconds.")

推荐阅读