Free online Python Code to Decode Twitter Snowflake ID tool. No signup required.
Free & instant 100% client-side No signup needed
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}")
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.
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.