Search code examples
gotimeinstagramunix-timestampdate-conversion

Instagram media ID to timestamp conversion


Instagram explains how they create their media ID in this blog post

https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c

Each of our IDs consists of: 41 bits for time in milliseconds (gives us 41 years of IDs with a custom epoch) 13 bits that represent the logical shard ID 10 bits that represent an auto-incrementing sequence, modulus 1024. This means we can generate 1024 IDs, per shard, per millisecond.

our ‘epoch’ begins on January 1st, 2011 not sure if that's the actual production value or only for the example

How can I get the timestamp back from a media ID?

I have this two media ids where I know the timestamp, but I need to extract it from others

2384288897814875714 2020-08-26T13:43:27Z

2383568809444681765 2020-08-25T13:52:46Z


Solution

  • playground

    package main
    
    import (
        "fmt"
        "time"
    )
    
    const (
        instaEpoch int64 = 1314220021721
        mediaID int64 = 2384288897814875714
    )
    
    func main()  {
        extractedTimestamp := mediaID >> (64-41)
        timeFromMediaID := extractedTimestamp + instaEpoch
        fmt.Println(time.Unix(timeFromMediaID/1000,0).UTC())
    }
    

    Output:

    2020-08-26 13:43:27 +0000 UTC
    

    You can just right shift the id to get the timestamp back. Then you have to add the miliseconds to the epoch instagram is using.