# Find historical bitcoin block number with unix timestamp

By sandwich · 5 Sep 2024
Canonical: https://sandwich.farm/writing/find-bitcoin-block-number-with-timestamp/ · Nostr: https://njump.me/naddr1qvzqqqr4gupzpem34u9stj8ftlxldl4n2qz5f5hmrnxns3uga86fpwe7u28ga4n0qyw8wumn8ghj7mr4de3kscn00qh8xctwv3mkjcmg9enxzundqyt8wumn8ghj7un9d3shjtnswf5k6ctv9ehx2aqq9pnxjmny943xjarrda5kuttzd3hkx6edde6k6cn9wgkhw6t5dqkhg6tdv4ehgctdwqh0jhfv

> Script to find historical block number from timestamp.

I have searched the web for "Find bitcoin block number from historical date" maybe 100 times in my life. 

**Never again.**

You'll need a bitcoin node for this to work. The script is fast. 

# Install

## WoT Install
_one liner_
```
# curl
curl -o fjb.sh https://gist.githubusercontent.com/dskvr/18252c16cf85c06c1ee6cb5ae04a3197/raw/34bad6a35d98501978c8cd0c25b1628db1191cfe/fjb.sh && chmod +x fjb.sh

#wget
wget -O fjb.sh https://gist.githubusercontent.com/dskvr/18252c16cf85c06c1ee6cb5ae04a3197/raw/34bad6a35d98501978c8cd0c25b1628db1191cfe/fjb.sh && chmod +x fjb.sh
```

## Trust no one.
_create file_
```
vi fjb.sh
#or
nano fjb.sh
```

_review, copy and past into file_
```
TIMESTAMP=$1
LOWER=0
UPPER=$(bitcoin-cli getblockcount)

while (( LOWER <= UPPER )); do
    MID=$(( (LOWER + UPPER) / 2 ))
    BLOCKHASH=$(bitcoin-cli getblockhash $MID)
    BLOCKTIME=$(bitcoin-cli getblockheader $BLOCKHASH | jq .time)

    if (( BLOCKTIME < TIMESTAMP )); then
        LOWER=$(( MID + 1 ))
    elif (( BLOCKTIME > TIMESTAMP )); then
        UPPER=$(( MID - 1 ))
    else
        echo "$BLOCKTIME"
        exit 0
    fi
done

echo "$UPPER"
```

_give executable permissions_
```
chmod +x ./fjb.sh
```

# Usage
```
./fjb.sh <timestampSeconds> 
```
_It returns block number only_

# Example
```
$: ./fjb.sh 1668779310
763719
```
