2

I want to take the blocks between give timestamps. currently I manually use

fromBlock: (await web3.eth.getBlockNumber()) - 12343
toBlock: (await web3.eth.getBlockNumber()) - 6172

For getting yesterday's blocks. Is there any way to get the blocks using web3 between the timestamps?

2

If you want the blocks between timestamp1 <= block.timestamp <= timestamp2, you can do a binary search:

  • over the highest fromBlock you can find that satisfies web3.eth.getBlock(fromBlock).timestamp <= timestamp1
  • over the smallest toBlock you can find that satisfies timestamp2 <= web3.eth.getBlock(fromBlock).timestamp

Then, depending on your Web3 version, you do:

| improve this answer | |
2

In case you need a binary search implementation, here it's for Python 3:

web3 = Web3(WebsocketProvider("...."))
a = 1484362538 # 01/14/2017 @ 2:55am (UTC)


def estimate_block_height_by_timestamp(timestamp):
    block_found = False
    last_block_number = 9682416
    close_in_seconds = 600

    while not block_found:
        block = web3.eth.getBlock(last_block_number)
        block_time = datetime.datetime.fromtimestamp(block.timestamp).date()
        difference_in_seconds = int((timestamp - block_time).total_seconds())

        block_found = abs(difference_in_seconds) < close_in_seconds

        if block_found:
            return last_block_number

        if difference_in_seconds < 0:
            last_block_number //= 2
        else:
            last_block_number = int(last_block_number * 1.5) + 1


block = estimate_block_height_by_timestamp(
    datetime.datetime.fromtimestamp(a).date()
)

print(block)

>>> 2994181
# https://etherscan.io/block/2994181
# Block time - Jan-14-2017 11:21:00 AM +UTC
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.