Quick Start - Basic Function
Here's the simplest Python function to decode a Twitter snowflake ID to a date:
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
Complete Implementation with Details
This enhanced version returns all the details about the Twitter ID:
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}")
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:
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']}")
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:
#!/usr/bin/env python3
"""
Twitter Snowflake ID Decoder CLI
Usage: python twitter_decoder.py
"""
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 ")
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
# 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
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
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
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 |