Created
July 23, 2024 16:06
-
-
Save sychou/088783f54fe06db8e9d42951101c43c2 to your computer and use it in GitHub Desktop.
Find Block Number by Timestamp
This file contains 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
from datetime import datetime | |
from web3 import Web3 | |
# Connect to a local Ethereum node | |
HTTP_PROVIDER='http://localhost:8545' | |
w3 = Web3(Web3.HTTPProvider(HTTP_PROVIDER)) | |
def find_block_number_by_timestamp(target_timestamp, tolerance=60): | |
""" | |
Find the block number closest to the target_timestamp. | |
""" | |
latest_block_number = w3.eth.block_number | |
lower_limit = 7414978 # Lowest number for which we have data | |
upper_limit = latest_block_number | |
while lower_limit <= upper_limit: | |
mid_block_number = (lower_limit + upper_limit) // 2 | |
mid_block_timestamp = w3.eth.get_block(mid_block_number).timestamp | |
# If the difference between mid block timestamp and target timestamp is within the tolerance | |
if abs(mid_block_timestamp - target_timestamp) <= tolerance: | |
return mid_block_number | |
# Adjust the search range | |
if mid_block_timestamp < target_timestamp: | |
lower_limit = mid_block_number + 1 | |
else: | |
upper_limit = mid_block_number - 1 | |
return None | |
# Example usage: | |
# dt_str = '2022-01-01 12:00:00' # replace with your desired datetime | |
# target_timestamp = get_unix_timestamp_from_datetime(dt_str) | |
# block_number = find_block_number_by_timestamp(target_timestamp) | |
# print(f"The block number closest to {dt_str} is {block_number}.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment