Search code examples
pythonpython-3.xunixtimeunix-timestamp

Convert UNIX timestamp to how long it was in seconds


I'm working on a project and I need help.

I'd like to calculate how long ago was posted an instagram image. Using their json api I can get by example:

      "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
          },

The highlight being the "taken_at_timestamp" which gives me when the image was uploaded in UNIX time, however what I'd like to do is get the current UNIX time with by example:

import time
int(time.time()) 

And then calculate in seconds how long ago (timezone independent) the image was uploaded from now? Is that possible? It's hard for me to get my head around UNIX and Epoch times and all of that :)


Solution

  • Just subtract taken_at_timestamp from time.time() to get the difference between two times in seconds.

    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.")