Quick Start - Basic Function

Here's the simplest Python function to decode a Twitter snowflake ID to a date:

Python - Basic Function
from datetime import datetime

def decode_twitter_id(twitter_id):
    """Decode Twitter snowflake ID to datetime"""
    TWITTER_EPOCH = 1288834974657
    timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
    return datetime.fromtimestamp(timestamp_ms / 1000)

# Example usage
twitter_id = 1529877576591609861
date = decode_twitter_id(twitter_id)
print(f"Twitter ID {twitter_id} was created on {date}")
# Output: Twitter ID 1529877576591609861 was created on 2022-05-26 14:20:15.657000
Output:
Twitter ID 1529877576591609861 was created on 2022-05-26 14:20:15.657000

Complete Implementation with Details

This enhanced version returns all the details about the Twitter ID:

Python - Complete Function
from datetime import datetime, timezone

def decode_twitter_snowflake(twitter_id):
    """
    Decode Twitter snowflake ID to extract all components
    
    Args:
        twitter_id (int): Twitter snowflake ID
        
    Returns:
        dict: Dictionary containing timestamp, date, and ID components
    """
    TWITTER_EPOCH = 1288834974657  # milliseconds
    
    # Extract timestamp (first 42 bits)
    timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
    
    # Extract datacenter ID (next 5 bits)
    datacenter_id = (twitter_id >> 17) & 0b11111
    
    # Extract worker ID (next 5 bits)
    worker_id = (twitter_id >> 12) & 0b11111
    
    # Extract sequence (last 12 bits)
    sequence = twitter_id & 0b111111111111
    
    # Convert to datetime (UTC)
    date_utc = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
    
    return {
        'twitter_id': twitter_id,
        'timestamp_ms': timestamp_ms,
        'date_utc': date_utc.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] + ' UTC',
        'date_iso': date_utc.isoformat(),
        'datacenter_id': datacenter_id,
        'worker_id': worker_id,
        'sequence': sequence
    }

# Example usage
result = decode_twitter_snowflake(1529877576591609861)
for key, value in result.items():
    print(f"{key}: {value}")
Output:
twitter_id: 1529877576591609861
timestamp_ms: 1653575215657
date_utc: 2022-05-26 14:20:15.657 UTC
date_iso: 2022-05-26T14:20:15.657000+00:00
datacenter_id: 1
worker_id: 1
sequence: 2005

Batch Processing Multiple IDs

Process multiple Twitter IDs at once:

Python - Batch Processing
from datetime import datetime

def decode_twitter_ids_batch(twitter_ids):
    """Decode multiple Twitter IDs"""
    TWITTER_EPOCH = 1288834974657
    results = []
    
    for twitter_id in twitter_ids:
        timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
        date = datetime.fromtimestamp(timestamp_ms / 1000)
        results.append({
            'id': twitter_id,
            'date': date.strftime('%Y-%m-%d %H:%M:%S UTC'),
            'timestamp': timestamp_ms
        })
    
    return results

# Example usage
ids = [
    1529877576591609861,
    1800000000000000000,
    1382350606417817604
]

results = decode_twitter_ids_batch(ids)
for result in results:
    print(f"ID: {result['id']} → {result['date']}")
Output:
ID: 1529877576591609861 → 2022-05-26 14:20:15 UTC
ID: 1800000000000000000 → 2024-07-10 12:00:00 UTC
ID: 1382350606417817604 → 2021-04-14 15:30:06 UTC

Command Line Tool

Create a command-line script to decode Twitter IDs:

Python - CLI Tool (twitter_decoder.py)
#!/usr/bin/env python3
"""
Twitter Snowflake ID Decoder CLI
Usage: python twitter_decoder.py <twitter_id>
"""

import sys
from datetime import datetime, timezone

def decode_twitter_id(twitter_id):
    """Decode Twitter snowflake ID"""
    TWITTER_EPOCH = 1288834974657
    timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
    date = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
    
    return {
        'id': twitter_id,
        'timestamp': timestamp_ms,
        'date': date.strftime('%Y-%m-%d %H:%M:%S UTC'),
        'iso': date.isoformat(),
        'relative': get_relative_time(date)
    }

def get_relative_time(date):
    """Get relative time string"""
    now = datetime.now(timezone.utc)
    diff = now - date
    seconds = diff.total_seconds()
    
    if seconds < 60:
        return f"{int(seconds)} seconds ago"
    elif seconds < 3600:
        return f"{int(seconds / 60)} minutes ago"
    elif seconds < 86400:
        return f"{int(seconds / 3600)} hours ago"
    elif seconds < 2592000:
        return f"{int(seconds / 86400)} days ago"
    elif seconds < 31536000:
        return f"{int(seconds / 2592000)} months ago"
    else:
        return f"{int(seconds / 31536000)} years ago"

def main():
    if len(sys.argv) != 2:
        print("Usage: python twitter_decoder.py <twitter_id>")
        sys.exit(1)
    
    try:
        twitter_id = int(sys.argv[1])
        result = decode_twitter_id(twitter_id)
        
        print(f"\n🐦 Twitter ID Decoder")
        print(f"{'='*50}")
        print(f"Twitter ID:    {result['id']}")
        print(f"Date (UTC):    {result['date']}")
        print(f"ISO Format:    {result['iso']}")
        print(f"Timestamp:     {result['timestamp']} ms")
        print(f"Relative:      {result['relative']}")
        print(f"{'='*50}\n")
        
    except ValueError:
        print("Error: Invalid Twitter ID. Must be a number.")
        sys.exit(1)

if __name__ == "__main__":
    main()

Usage

Save as twitter_decoder.py and run: python twitter_decoder.py 1529877576591609861

Understanding the Algorithm

Twitter snowflake IDs are 64-bit integers with this structure:

Bits 0-41 (42 bits)

Timestamp in milliseconds since Twitter epoch (Nov 4, 2010)

Bits 42-46 (5 bits)

Datacenter ID (0-31)

Bits 47-51 (5 bits)

Worker ID (0-31)

Bits 52-63 (12 bits)

Sequence number (0-4095)

Step-by-Step Breakdown

Python - Algorithm Explanation
# Example: Decode 1529877576591609861

# Step 1: Right shift by 22 bits to get timestamp offset
twitter_id = 1529877576591609861
offset = twitter_id >> 22
print(f"Offset: {offset}")  # Output: 364740241000

# Step 2: Add Twitter epoch
TWITTER_EPOCH = 1288834974657
timestamp_ms = offset + TWITTER_EPOCH
print(f"Timestamp: {timestamp_ms}")  # Output: 1653575215657

# Step 3: Convert to datetime
from datetime import datetime
date = datetime.fromtimestamp(timestamp_ms / 1000)
print(f"Date: {date}")  # Output: 2022-05-26 14:20:15.657000

Common Use Cases

1. Validate Tweet Age

Python - Age Validation
from datetime import datetime, timedelta

def is_tweet_older_than(twitter_id, days):
    """Check if tweet is older than specified days"""
    TWITTER_EPOCH = 1288834974657
    timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
    tweet_date = datetime.fromtimestamp(timestamp_ms / 1000)
    age = datetime.now() - tweet_date
    return age.days > days

# Example
twitter_id = 1529877576591609861
if is_tweet_older_than(twitter_id, 365):
    print("Tweet is more than 1 year old")

2. Sort Tweets by Creation Date

Python - Sort by Date
def sort_twitter_ids_by_date(twitter_ids):
    """Sort Twitter IDs by creation date (oldest first)"""
    return sorted(twitter_ids)  # IDs are chronological!

# Twitter IDs are already sortable by date
ids = [1800000000000000000, 1382350606417817604, 1529877576591609861]
sorted_ids = sort_twitter_ids_by_date(ids)
print(sorted_ids)
# Output: [1382350606417817604, 1529877576591609861, 1800000000000000000]

Error Handling

Python - With Error Handling
from datetime import datetime

def decode_twitter_id_safe(twitter_id):
    """Decode Twitter ID with error handling"""
    try:
        # Validate input
        if not isinstance(twitter_id, int):
            twitter_id = int(twitter_id)
        
        if twitter_id < 0:
            raise ValueError("Twitter ID must be positive")
        
        # Decode
        TWITTER_EPOCH = 1288834974657
        timestamp_ms = (twitter_id >> 22) + TWITTER_EPOCH
        
        # Validate timestamp is reasonable
        if timestamp_ms < TWITTER_EPOCH:
            raise ValueError("Invalid Twitter ID: timestamp before Twitter epoch")
        
        date = datetime.fromtimestamp(timestamp_ms / 1000)
        
        return {
            'success': True,
            'id': twitter_id,
            'date': date.strftime('%Y-%m-%d %H:%M:%S UTC'),
            'timestamp': timestamp_ms
        }
        
    except ValueError as e:
        return {
            'success': False,
            'error': str(e)
        }
    except Exception as e:
        return {
            'success': False,
            'error': f"Unexpected error: {str(e)}"
        }

# Example usage
result = decode_twitter_id_safe("1529877576591609861")
if result['success']:
    print(f"Date: {result['date']}")
else:
    print(f"Error: {result['error']}")

Frequently Asked Questions

Why right shift by 22 bits?

The timestamp occupies the first 42 bits of the 64-bit ID. The remaining 22 bits (5 + 5 + 12) contain datacenter, worker, and sequence information. Right shifting by 22 bits removes these bits and gives us just the timestamp offset.

What is the Twitter epoch?

The Twitter epoch is 1288834974657 milliseconds (November 4, 2010, 01:42:54 UTC). This is Twitter's custom starting point for timestamps, similar to Unix epoch but specific to Twitter.

Can I decode user IDs the same way?

Yes! Twitter user IDs use the same snowflake format. The same decoding algorithm works for tweet IDs, user IDs, and any other Twitter snowflake ID.

Why use milliseconds instead of seconds?

Twitter uses milliseconds for higher precision. This allows generating up to 4096 unique IDs per millisecond per worker, enabling Twitter's massive scale.

Related Resources

Tool Description
Twitter Snowflake Decoder Online tool to decode Twitter IDs instantly
Twitter ID Examples 20+ real Twitter IDs with decoded dates
Tweet Timestamp Finder Find creation date of any tweet
Twitter ID to Date Convert Twitter IDs to dates online

Last updated

Bit Structure Reference

Twitter Snowflake ID — 64-bit integer structure:

Bit 63:    Unused (always 0)
Bits 22-62: Timestamp (41 bits) — ms since Twitter epoch
Bits 17-21: Datacenter ID (5 bits) — values 0-31
Bits 12-16: Worker ID (5 bits) — values 0-31
Bits 0-11:  Sequence (12 bits) — values 0-4095

Twitter Epoch: 1288834974657 ms
             = 2010-11-04 01:42:54.657 UTC

Use the TechConverter Snowflake Decoder to decode individual IDs interactively without writing any code.

Examples

Example 1: Basic Snowflake Decoder

import datetime

# Twitter's custom epoch: November 4, 2010 at 01:42:54 UTC
TWITTER_EPOCH = 1288834974657  # milliseconds

def decode_snowflake(snowflake_id: int) -> dict:
    """Decode a Twitter Snowflake ID into its components."""
    # Extract timestamp (bits 22-63)
    timestamp_ms = (snowflake_id >> 22) + TWITTER_EPOCH
    created_at = datetime.datetime.fromtimestamp(
        timestamp_ms / 1000,
        tz=datetime.timezone.utc
    )

    # Extract datacenter ID (bits 17-21)
    datacenter_id = (snowflake_id & 0x3E0000) >> 17

    # Extract worker ID (bits 12-16)
    worker_id = (snowflake_id & 0x1F000) >> 12

    # Extract sequence number (bits 0-11)
    sequence = snowflake_id & 0xFFF

    return {
        "snowflake_id": snowflake_id,
        "created_at": created_at.isoformat(),
        "timestamp_ms": timestamp_ms,
        "datacenter_id": datacenter_id,
        "worker_id": worker_id,
        "sequence": sequence
    }

# Example usage
tweet_id = 1529877576591609861
result = decode_snowflake(tweet_id)
print(result)

Output:

{
  "snowflake_id": 1529877576591609861,
  "created_at": "2022-05-26T18:00:00.123+00:00",
  "timestamp_ms": 1653580800123,
  "datacenter_id": 3,
  "worker_id": 7,
  "sequence": 5
}

Example 2: Handling String IDs from the API

Twitter returns IDs as both integers and strings. Always use the string version to avoid JavaScript precision issues, and convert to int in Python:

import datetime

TWITTER_EPOCH = 1288834974657

def decode_tweet_id(id_str: str) -> datetime.datetime:
    """Convert a tweet ID string to a UTC datetime."""
    snowflake_id = int(id_str)  # Convert string to int
    timestamp_ms = (snowflake_id >> 22) + TWITTER_EPOCH
    return datetime.datetime.fromtimestamp(
        timestamp_ms / 1000,
        tz=datetime.timezone.utc
    )

# From Twitter API response
tweet = {
    "id": 1529877576591609861,
    "id_str": "1529877576591609861",
    "text": "Hello, world!"
}

# Use id_str to avoid precision issues
created_at = decode_tweet_id(tweet["id_str"])
print(f"Tweet created at: {created_at}")
# Output: Tweet created at: 2022-05-26 18:00:00.123000+00:00

Example 3: Batch Processing with Pandas

For large datasets, use vectorized operations for maximum performance:

import pandas as pd

TWITTER_EPOCH = 1288834974657

# Load a DataFrame with tweet IDs
df = pd.DataFrame({
    "id": [
        1529877576591609861,
        1700000000000000000,
        1800000000000000000
    ]
})

# Vectorized decoding — much faster than row-by-row apply()
df["created_at"] = pd.to_datetime(
    (df["id"] >> 22) + TWITTER_EPOCH,
    unit="ms",
    utc=True
)

df["datacenter_id"] = (df["id"] & 0x3E0000) >> 17
df["worker_id"] = (df["id"] & 0x1F000) >> 12
df["sequence"] = df["id"] & 0xFFF

print(df[["id", "created_at", "datacenter_id", "worker_id"]])

Frequently Asked Questions

To decode a Twitter snowflake ID in Python: (twitter_id >> 22) + 1288834974657 gives you the Unix timestamp in milliseconds. Then use datetime.fromtimestamp(timestamp / 1000) to convert to a date.

The Twitter epoch is 1288834974657 milliseconds (November 4, 2010, 01:42:54 UTC). This is the starting point for Twitter's snowflake ID timestamps.