Created
June 20, 2025 21:06
-
-
Save mqudsi/334741b453bac3d6d21e94434a4bdf81 to your computer and use it in GitHub Desktop.
Twitter snowflake id timestamp extraction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
/// Takes either the tweet ID only or the full URL to a post. | |
/// Returns the UTC timestamp. | |
function extract_tweet_timestamp($input) { | |
$twitter_epoch = 1288834974657; // in milliseconds | |
// Extract the snowflake id | |
if (preg_match('~(twitter\.com|x\.com)/[^/]+/status/([0-9]+)~', $input, $m)) { | |
$snowflake = $m[2]; | |
} elseif (is_numeric($input)) { | |
$snowflake = $input; | |
} else { | |
throw new InvalidArgumentException("Could not extract tweet ID."); | |
} | |
// Convert input to string to use as bignum | |
if (!is_string($snowflake)) { | |
$snowflake = (string)$snowflake; | |
} | |
if (function_exists('bcdiv')) { | |
// Get first 41 bits | |
$timestamp_ms_part = bcdiv($snowflake, bcpow('2', '22')); | |
// Add epoch, get timestamp in ms | |
$unix_ms = bcadd($timestamp_ms_part, $twitter_epoch); | |
// Get seconds and milliseconds | |
$seconds = bcdiv($unix_ms, '1000', 3); | |
return $seconds; | |
} else { | |
// Assume 64-bit PHP_INT_MAX | |
$snowflake_int = is_numeric($snowflake) ? (int)$snowflake : 0; | |
$timestamp_ms_part = $snowflake_int >> 22; | |
$unix_ms = $timestamp_ms_part + $twitter_epoch; | |
$seconds = $unix_ms / 1000.0; | |
return $seconds; | |
} | |
} | |
echo date('c', extract_tweet_timestamp($argv[1])); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment